2013-09-26 63 views

Trả lời

84

Sử dụng phiên bản quá tải của indexOf(), trong đó có các Indes bắt đầu từ tham số thứ 2:

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

Quá tải này bắt đầu tìm kiếm chuỗi con từ chỉ mục đã cho.

+0

gì xảy ra nếu sự xuất hiện nhiều hơn hai lần? –

+1

Sau đó, không có gì đặc biệt xảy ra, nó vẫn sẽ xảy ra lần thứ hai. –

+0

Còn về chỉ số xảy ra lần thứ ba! –

0

tôi nghĩ rằng một vòng lặp có thể được sử dụng.

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 
0

Bạn có thể viết một hàm trả về mảng các vị trí xảy ra, Java có String.regionMatches chức năng mà là khá tiện dụng

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; 
} 
Các vấn đề liên quan