本文介绍了字符串中所有出现的字符的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码会打印2
String word = "bannanas";
String guess = "n";
int index;
System.out.println(
index = word.indexOf(guess)
);
我想知道如何获取字符串banannas"中所有n"(猜测")的索引
I would like to know how to get all the indexes of "n" ("guess") in the string "bannanas"
预期结果是:[2,3,5]
推荐答案
这应该在 Peter Lawrey 的解决方案 了.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
它也可以作为 for
循环来完成:
It can also be done as a for
loop:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[注意:如果guess
可以长于一个字符,那么可以通过分析guess
字符串,遍历word
代码> 比上述循环快.这种方法的基准是 Boyer-Moore 算法.然而,支持使用这种方法的条件似乎不存在.]
[Note: if guess
can be longer than a single character, then it is possible, by analyzing the guess
string, to loop through word
faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]
这篇关于字符串中所有出现的字符的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!