-3

在甲骨文中:

情况1:

SELECT INSTR('Viveok Srinivoasamoorthy','o',15,1) FROM DUAL;

输出:19

案例2:SELECT INSTR('Viveok Srinivoasamoorthy','o',15,2) FROM DUAL; 输出:20

同样,我需要开发一个具有 4 个参数(字符串、子字符串、start_position 和 nthoccurrence)的 java 程序来实现。

这是我尝试过的代码,但在下面的代码中我找不到第 n 次出现:

public static int nthoccur(String str1,String str2,int occurs )
{
    int f_occurance=0;
    f_occurance=str1.indexOf(str2, occurs-1)+1;
    System.out.println("f_occurance Value------*** "+f_occurance);
    return f_occurance;     
} 

public static void main(String args[])
{

int resultinst=nthoccur("Viveok Srinivoasamoorthy","o",15);
System.out.println(resultinst);
}

输出:

f_occurance Value------*** 19
19

现在我想使用java程序从字符串的第15个位置找到第二个出现的“o”。如何使用 Java 程序实现案例 2?

4

2 回答 2

1

这是一个应该模仿INSTR的方法。

评论将帮助您逐步了解它的工作原理:

public static int instr(final String str, final String substring, int position, final int occurrence) {

    // matches counter
    int count = 0;
    // index of last match
    int indexFound = 0;

    // while we haven't reached the desired match count, and we still find another match
    while (count != occurrence && (indexFound = str.indexOf(substring, position)) != -1)

    {
        // increment match count
        count++;
        // position the next search index, to the end of the current match
        position = indexFound + substring.length();

    }

    if (count == occurrence) {
        // the number of occurrences was matched, return the last match index
        return indexFound + 1; // index in Java starts at 0
    } else {
        // the number of occurrences was not matched, return 0
        return 0;
    }

}
于 2016-03-29T13:54:10.090 回答
0

这是另一种方式:-1 表示没有发生。 getInstring(String input, String substr, int start, int occurence) { char[] tempstring = input.substring(start).replaceAll(substr, "-").toCharArray(); int occurindex = 0; int counter = 0; for (int i = 0; i < tempstring.length; i++) { if (":-".equals(":" + tempstring[i])) { occurindex++; counter = i; } if (occurindex == occurence) { break; } } return counter == 0 ? -1 : counter + start + 1; }

于 2016-03-29T14:27:21.893 回答