小编srm*_*mjr的帖子

indexOf查找String中所有出现的单词

我正在尝试使用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 -----");
Run Code Online (Sandbox Code Playgroud)

java string loops indexof

3
推荐指数
2
解决办法
2万
查看次数

标签 统计

indexof ×1

java ×1

loops ×1

string ×1