2

特定のテキスト文字列の検索フレーズのすべての文字位置を取得する最良の方法は何ですか?

たとえば、私たちが持っているとしましょう"the red cat is watching the red car stopped at the red stop sign"

INPUT: 「赤」 OUTPUT: [5, 29, 52]

4

1 に答える 1

2

文字列クラスのindexOfメソッドを使用できます。

String haystack = "the red cat is watching the red car stopped at the red stop sign";
String needle = "red";
int idx = 0, pos;
while( (pos = haystack.indexOf(needle,idx)) != -1) {
        System.out.println(pos+1);
        idx += pos+1;     
}

見る

于 2011-11-20T07:27:29.303 に答える