以下代碼將打印2String word = "bannanas";String guess = "n";int index;System.out.println( index = word.indexOf(guess));我想知道如何在字符串“ bannanas”中獲取“ n”(“ guess”)的所有索引預期結果將是: [2,3,5]
3 回答

陪伴而非守候
TA貢獻1757條經驗 獲得超8個贊
這應該打印位置的名單沒有-1在這個月底彼得Lawrey的解決方案 已經過。
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
也可以for循環執行:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[注意:如果guess可以長于單個字符,那么通過分析guess字符串,可以word比上述循環更快地循環。這種方法的基準是Boyer-Moore算法。但是,似乎不存在使用這種方法的條件。]

四季花海
TA貢獻1811條經驗 獲得超5個贊
請嘗試以下操作(現在末尾不會打印-1?。?/p>
int index = word.indexOf(guess);
while(index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index+1);
}
添加回答
舉報
0/150
提交
取消