私はこのソースを使用しています:
String fulltext = "I would like to create a book reader have create, create ";
String subtext = "create";
int i = fulltext.indexOf(subtext);
しかし、私は最初のインデックスのみを見つけます、文字列内のすべての最初のインデックスを見つける方法は?(この場合は3つのインデックス)
私はこのソースを使用しています:
String fulltext = "I would like to create a book reader have create, create ";
String subtext = "create";
int i = fulltext.indexOf(subtext);
しかし、私は最初のインデックスのみを見つけます、文字列内のすべての最初のインデックスを見つける方法は?(この場合は3つのインデックス)
最初のインデックスを見つけたらindexOf
、開始インデックスを2番目のパラメータとして受け取るオーバーロードバージョンを使用します。
public int indexOf(int ch, int fromIndex)
指定された文字が最初に出現するこの文字列内のインデックスを返し、指定されたインデックスから検索を開始します。
indexOf
が返されるまでこれを繰り返します-1
。これは、一致するものがこれ以上見つからないことを示します。
開始位置を受け入れるバージョンの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);
パターンとマッチャーで正規表現を使用できます。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());
}
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
}