【问题标题】:indexOf to find all occurrences of a word in a StringindexOf 查找字符串中所有出现的单词
【发布时间】:2016-12-01 21:23:53
【问题描述】:

我正在尝试使用 indexOf 来查找句子中所有出现的字符“the”。例如,如果句子是“The other day I went over there”,它应该返回 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 -----");

【问题讨论】:

  • 我建议使用正则表达式进行搜索。
  • 您介意解释一下您所说的正则表达式是什么意思吗?
  • 重复问题,该问题之前在this post中回答过

标签: java string loops indexof


【解决方案1】:

您采取了一种复杂的方法。试试这个:

int count = str.split("the", -1).length - 1;

如果你绝对必须使用indexOf()

str = str.toLowerCase();
int count = 0;
for (int i = str.indexOf("the"); i >= 0; i = str.indexOf("the", i + 1))
    count++;

【讨论】:

  • 感谢您的意见,但我想专门使用 indexOf
  • 谢谢。是 .toLowerCase();用于搜索单词的所有实例,不考虑大小写?
  • @srmjr 是的,您的示例表明搜索应该不区分大小写。先做小写操作,让代码更易读,速度更快
  • 请注意,如果目标字符串位于字符串末尾,则使用str.split 不会给出正确的计数。如果您不能保证目标字符串不会出现在字符串的末尾,则不应使用此选项。在这种情况下,str = "kkkthekkkthe"; int count = str.split("the").length - 1;,count 返回 1 而不是 2。
  • @LynchChen 好点。固定答案,现在调用保留结果尾随空白元素的拆分版本。请参阅live demo,它为您的示例返回 2。
【解决方案2】:

indexOf can take a second argument 表示从字符串的哪里开始。因此,在找到第一个匹配项后,您可以告诉 indexOf 仅搜索该索引之后的字符串,等等。

这段代码应该可以工作:

public static void main(String[] args) {
    String theString = "The other day I went over there.";
    theString = theString.toLowerCase();

    int index = -1;
    int count = 0;

    while (true) {
        index = theString.indexOf("the", index + 1);
        if (index == -1) {
            break;
        } else {
            count += 1;
        }
    }

    System.out.printf("The string 'the' was found %d times.\n", count);

    // Output:
    // The string 'the' was found 3 times.
}

【讨论】:

    【解决方案3】:

    您可以跟踪索引:

    int index = theString.indexOf("the");
    while(index >= 0) {
        index = theString.indexOf("the", index+1);
        counter2++;
    }
    

    【讨论】:

    • 不需要两次indexOf() 调用:for (int idx = 0; (idx = theString.indexOf("the", idx)) >= 0; idx++) { counter2++; }
    【解决方案4】:

    indexOf(String str) 方法查找str第一次 出现的索引。因此,如果您想找到 所有 str 的出现,那么我建议您只执行一个循环,一旦找到 str 的实例并在其中剪切字符串并查找 str再次在theString 中,直到它不再在theString 中。这是它的样子,

    int index = theString.indexOf("the")
    int count = 0;
    while(index >= 0 && theString.length() > 0){
         count++;
         theString = theString.substring(0, index + "the".length());
         index = theString.indexOf("the");
    }
    

    【讨论】:

    • 这是错误的。 while 循环将陷入无限循环,因为变量 index 永远不会更新。
    • @JonathanJeffrey 谢谢,我刚刚修好了。这是我的一个懒惰错误。
    【解决方案5】:

    如果你想专门使用indexOf(我猜这是为了赋值),你可以使用递归方法。

    public static String numMatches (String str, String query) {
        int index = str.indexOf(query);
        if (index == -1) 
            return 0;
        else
            return 1 + numMatches(str.substring(index + query.length), query);
    }
    

    【讨论】:

      【解决方案6】:

      也许你可以这样做,你可以使用 indexOf(String str)

      String word = "We are students of the Department of Informatics. All students should know how to program in Java and C.";
      
          int findit = word.indexOf("students");
          int count = 0;
      
          for(int i=0; i<=findit; i++)
          {
      
              findit = word.indexOf("students" , findit + 1);
      
              count = count + 1;
      
          }
      
          System.out.print(count);
      

      【讨论】:

        【解决方案7】:

        这会检查一个字符串在一个字符串中出现了多少次。

                     String str = oIn.nextLine();
                     String st = oIn.nextLine();
                     int countS = 0;
                     int index3 = str3.indexOf(st);
                     while (index >= 0){
                     index = str.indexOf(st, index+1);
                     countS++;          
                     }
                     System.out.println("The number of occurrences of "+st +" in the string " +str3 +" are "+countS);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-21
          • 2016-05-13
          • 2012-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多