4

私はこのソースを使用しています:

String fulltext = "I would like to create a book reader  have create, create ";

String subtext = "create";
int i = fulltext.indexOf(subtext);

しかし、私は最初のインデックスのみを見つけます、文字列内のすべての最初のインデックスを見つける方法は?(この場合は3つのインデックス)

4

4 に答える 4

9

最初のインデックスを見つけたらindexOf、開始インデックスを2番目のパラメータとして受け取るオーバーロードバージョンを使用します。

public int indexOf(int ch, int fromIndex)指定された文字が最初に出現するこの文字列内のインデックスを返し、指定されたインデックスから検索を開始します。

indexOfが返されるまでこれを繰り返します-1。これは、一致するものがこれ以上見つからないことを示します。

于 2013-02-26T15:31:16.753 に答える
4

開始位置を受け入れるバージョンのindexOfを使用します。見つからなくなるまでループで使用します。

String fulltext = "I would like to create a book reader  have create, create ";
String subtext = "create";
int ind = 0;
do {
    int ind = fulltext.indexOf(subtext, ind);
    System.out.println("Index at: " + ind);
    ind += subtext.length();
} while (ind != -1);
于 2013-02-26T15:33:39.423 に答える
4

パターンとマッチャーで正規表現を使用できます。Matcher.find()次の一致を見つけようとしMatcher.start()、一致の開始インデックスを提供します。

Pattern p = Pattern.compile("create");
Matcher m = p.matcher("I would like to create a book reader  have create, create ");

while(m.find()) {
    System.out.println(m.start());
}
于 2013-02-26T15:35:49.130 に答える
0

whileループを作成し、を使用しますindexof(String str, int fromIndex)

String fulltext = "I would like to create a book reader  have create, create ";
int i = 0;
String findString = "create";
int l = findString.length();
while(i>=0){

     i = fulltext.indexOf(findString,i+l);
     //store i to an array or other collection of your choice
 }
于 2013-02-26T15:32:40.293 に答える