在 Java 中查找字符串中子字符串的第二次出现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19035893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:34:47  来源:igfitidea点击:

Finding second occurrence of a substring in a string in Java

javastringsubstringindexof

提问by AmanArora

We are given a string, say, "itiswhatitis"and a substring, say, "is". I need to find the index of 'i'when the string "is"occurs a second time in the original string.

我们得到一个字符串,例如,"itiswhatitis"和一个子字符串,例如,"is"。我需要找到'i'字符串"is"在原始字符串中第二次出现的索引。

String.indexOf("is")will return 2 in this case. I want the output to be 10 in this case.

String.indexOf("is")在这种情况下将返回 2。在这种情况下,我希望输出为 10。

采纳答案by Rohit Jain

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

使用 的重载版本indexOf(),它将起始索引 (fromIndex) 作为第二个参数:

str.indexOf("is", str.indexOf("is") + 1);

回答by Jeroen Vannevel

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

此重载开始从给定索引中查找子字符串。

回答by Pravat Panda

i think a loop can be used.

我认为可以使用循环。

1 - check if the last index of substring is not the end of the main string.
2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string
3 - repeat the steps in a loop

回答by namnt

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

您可以编写一个函数来返回出现位置的数组,Java 有 String.regionMatches 函数,非常方便

public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

回答by To Kra

I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()

我正在使用: Apache Commons Lang:StringUtils.ordinalIndexOf()

StringUtils.ordinalIndexOf("Java Language", "a", 2)