indexOf 查找字符串中某个单词的所有出现位置

2024-03-23

我正在尝试使用 indexOf 查找句子中出现的所有字符“the”。例如,如果句子是“那天我去了那里”,则应返回 3。

我能够做到这一点,直到找到第一个索引,但我不确定如何编写循环。我最初有一个 for 循环来搜索整个字符串,但它返回完整的字符串字符长度,而不是指定字符的出现次数。如何编写一个循环来查找该单词的所有出现位置?谢谢。

import java.util.Scanner;

public class TheFinder
{
    public static void main (String[] args)
    {
        String theString = "";
        Scanner enter = new Scanner(System.in);

        System.out.println("Please enter a sentence: ");
        theString = enter.nextLine();
        int counter2 = 0;
        theString.indexOf("the");

        if (theString.indexOf("the")!= -1)
        counter2++;



        System.out.printf("The characters 'the' were found %d times", counter2);
        System.out.println();

        System.out.println("This was programmed by -----");

您可以跟踪索引:

int index = theString.indexOf("the");
while(index >= 0) {
    index = theString.indexOf("the", index+1);
    counter2++;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

indexOf 查找字符串中某个单词的所有出现位置 的相关文章

随机推荐