your programing

Java의 문자열에서 두 번째 하위 문자열 찾기

lovepro 2020. 12. 26. 16:14
반응형

Java의 문자열에서 두 번째 하위 문자열 찾기


우리는 문자열 say, "itiswhatitis"그리고 부분 문자열, say,를 받았습니다 "is". 원래 문자열에서 'i'문자열 "is"이 두 번째로 발생하는 경우 의 인덱스를 찾아야 합니다.

String.indexOf("is")이 경우 2를 반환합니다. 이 경우 출력이 10이되기를 원합니다.


indexOf()시작 색인 (fromIndex)을 두 번째 매개 변수로 사용하는 오버로드 된 버전을 사용합니다 .

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

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

이 오버로드는 주어진 인덱스에서 하위 문자열을 찾기 시작합니다.


나는 사용하고 있습니다 : Apache Commons Lang : StringUtils.ordinalIndexOf ()

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

루프를 사용할 수 있다고 생각합니다.

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

발생 위치 배열을 반환하는 함수를 작성할 수 있습니다. 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;
}

참조 URL : https://stackoverflow.com/questions/19035893/finding-second-occurrence-of-a-substring-in-a-string-in-java

반응형