检查ArrayList<String>中的每个字母是否是某个字符?

Check if each letter in ArrayList<String> is a certain character?

首先,我是 Whosebug 的超级新手(请原谅我丑陋的格式),并且只有几年的编程经验(总共大约 6 次编程 类)

我正在做刽子手项目。我选择对其中的一些使用 StringBuilder。例如,我想检查 char chosenLetter = 'C'StringBuilder chosenWord = new StringBuilder("Ceramics");

中的索引

理想情况下,我会有一个 for 循环来遍历 StringBuilder 单词“Ceramics”并告诉我索引 07。我绝对想不通。我试过使用 indexOf() 函数,但出于某种原因,如果我使用

for (int i = 0; i < chosenWord.length(); i++) {
     if (chosenWord.indexOf(chosenLetter, i) != -1) {
        System.out.println("This should be a match at index " + i);
    }
}

它会打印出例如:

This should be a match at index 0

This should be a match at index 1

This should be a match at index 2

This should be a match at index 3

This should be a match at index 4

This should be a match at index 5

This should be a match at index 6

This should be a match at index 7

This should be a match at index 8

而不是

This should be a match at index 0

This should be a match at index 7

有什么办法可以做到这一点吗?谢谢。

再一次,对于丑陋的格式感到抱歉。如果有任何关于澄清的问题,我很乐意尝试澄清!

看看这个

 for (int i = 0; i < chosenWord.length(); i++) {
    if (chosenWord.charAt(i) == chosenLetter) {
    System.out.println("This should be a match at index " + i);
    }
    }

这将打印出您想要的输出

你可以使用StringBuilder#indexOf(String, int),但你需要确保在每次匹配成功后递增index位置,否则你将陷入无限循环...

StringBuilder sb = new StringBuilder("ceramics");
int index = 0;
while ((index = sb.indexOf("c", index)) >= 0) {
    System.out.println(index);
    index++;
}

还应注意,这是一个区分大小写的搜索,如您所见,我将文本全部设为小写,以便我可以捕获位置 06

您第一次尝试的基本问题是您实际上忽略了 indexOf

的结果
if (chosenWord.indexOf(chosenLetter, i) != -1) {
    System.out.println("This should be a match at index " + i);

然后打印 i,因此在每次迭代中,您都会得到 06 的结果,因此它打印 0 结果的原因] - 6

所以...

i = 0; chosenWord.indexOf(chosenLetter, i) == 6, print 0
i = 1; chosenWord.indexOf(chosenLetter, i) == 6, print 1
i = 2; chosenWord.indexOf(chosenLetter, i) == 6, print 2
i = 3; chosenWord.indexOf(chosenLetter, i) == 6, print 3
i = 4; chosenWord.indexOf(chosenLetter, i) == 6, print 4
i = 5; chosenWord.indexOf(chosenLetter, i) == 6, print 5
i = 6; chosenWord.indexOf(chosenLetter, i) == 6, print 6
i = 7; chosenWord.indexOf(chosenLetter, i) == -1, ignored

你实际上不需要外部循环,你只需要继续循环直到 indexOf< 0,如上所示...

您看到该输出的原因是因为 indexOf will return 0 for i = 0 and 6 for i = 1 to 7. In all those cases, the return is different from -1, which satisfies the if statement. Consider using charAt,与@ppuskar 建议的方式相同。