【问题标题】:Count the occurrences of a letter in a string计算字符串中某个字母出现的次数
【发布时间】:2013-10-25 04:06:27
【问题描述】:

我正在尝试用 Java 编写一个 for 循环来计算字符串中字母的出现次数。用户将输入要计数的字母和要搜索的字符串。这是一个非常基本的代码,我们还没有接触到数组或其他很多东西。 (我意识到我两次声明了信,但此时我的大脑已经死了)这是我迄今为止尝试过的并且遇到了麻烦,感谢任何帮助:

好的,我根据建议更改了我的代码,但现在它只读取我句子的第一个单词?

import java.util.Scanner;

public class CountCharacters {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    char letter;
    String sentence = "";
    System.out.println("Enter a character for which to search");
    letter = in.next().charAt(0);
    System.out.println("Enter the string to search");
    sentence = in.next();

    int count = 0;
    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);
        if (ch == letter) {
            count++;
        }
    }
    System.out.printf("There are %d occurrences of %s in %s", count,
            letter, sentence);

}
}

【问题讨论】:

  • 既然你的代码不能编译,你怎么知道它不起作用?它没有,但你真的尝试过吗?如果有,请解释问题所在(除了重复声明)。

标签: java for-loop


【解决方案1】:

我看到了几个问题。首先你有两个同名的变量。

第二次你的if条件检查句子的长度是否大于0,而不是检查字符是否相等。

Scanner in = new Scanner(System.in);

char inLetter = "";
String sentence = "";
System.out.println("Enter a character for which to search");
inLetter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();

int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
    char ch = sentence.charAt(i);
    if (inLetter == ch) {
        letter++;
    }
}

System.out.print(sentence.charAt(letter));

我还强烈建议验证输入(在上面的示例中未完成),而不是仅仅假设您从第一个输入中获得 1 个字符,在第二个输入中获得 1 个句子。

【讨论】:

    【解决方案2】:

    您的if (sentence.length() &lt;= 0) { 不正确。改变你的条件:

    System.out.println("Enter a character for which to search");
    letter = in.next();
    System.out.println("Enter the string to search");
    sentence = in.next();
    char searchLet=letter.charAt(0); // Convert String to char
    int letter = 0;
    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);
        if (searchLet== ch) {  // Check the occurrence of desired letter.
            letter++;
        }
    }
    
    System.out.print(sentence.charAt(letter));
    

    【讨论】:

      【解决方案3】:
      if (sentence.length() <= 0) {
                  letter++;
      }
      

      您程序中的上述部分代码是错误的。除非您输入一个空字符串,否则这永远不会成立。

      而且基本上这不是正确的逻辑。您将不得不使用直接比较。

      【讨论】:

        【解决方案4】:

        无需循环:

            String sentence = "abcabcabcd";
            String letter = "b";
            int numOfOccurences = sentence.length() - 
                                  sentence.replaceAll(letter, "").length();
            System.out.println("numOfOccurences = "+numOfOccurences);
        

        输出:

        numOfOccurences = 3
        

        【讨论】:

          【解决方案5】:

          试试这个

          忘记String letter = "" 忘记letter = in.next()

              // There's no nextChar() method, so this is a work aroung
              char ch = in.findWithinHorizon(".", 0).charAt(0);
          
              int letter = 0;
              for (int i = 0; i < sentence.length(); i++) {
          
                  if (sentence.charAt(i) == ch) {
                      letter++;
                  }
              }
          
              System.out.println(letter);  // print number of times letter appears
          
              // You don't want this
              System.out.print(sentence.charAt(letter)); // Makes no sense
          

          【讨论】:

            【解决方案6】:

            试试这个:

            Char letter = '';
            String sentence = "";
            System.out.println("Enter a character for which to search");
            letter = in.next().charAt(0);
            System.out.println("Enter the string to search");
            sentence = in.next();
            
            int count= 0;
            for (int i = 0; i < sentence.length(); i++) {
                char ch = sentence.charAt(i);
                if (ch==letter) {
                    count++;
                }
            }
            System.out.print(letter+" occurance:"+count);
            

            【讨论】:

            • 不能申请 in.next();带字符。
            【解决方案7】:
            1. 您需要知道要搜索的字符。您可以使用 char charToSearch = letter.toCharArray()[0];
            2. 定义一个变量,例如 count 来计算给定字符串中某个字母的出现次数。
            3. 循环字符串并比较每个char,如果char等于要搜索的char,则count++;

            例子--->

            int count = 0;
            char charToSearch = letter.toCharArray()[0];
            for (int i = 0; i < sentence.length(); i++) {
                if (sentence.charAt(i) ==  charToSearch) {
                    count++;
                }
            }
            
            System.out.printf("Occurrences of a %s in %s is %d", letter, sentence, count);
            

            【讨论】:

              【解决方案8】:

              希望这对你有帮助。

              import java.util.Scanner;
              
              public class CountCharacters {
                  public static void main(String[] args) {
              
                      Scanner in = new Scanner(System.in);
              
                      System.out.println("Enter the string to search");
                      String sentence = in.nextLine();
              
                      System.out.println("Enter a character for which to search");
                      String letter = in.next();
              
                      int noOfOccurance = 0;
              
                      for (int i = 0; i < sentence.length(); i++) {
                          char dh=letter.charAt(0);
                          char ch = sentence.charAt(i);
                          if (dh==ch) {
                             noOfOccurance++;
                          }
                     }
                     System.out.print(noOfOccurance);
                  }
              }
              

              样本输入输出

              Enter the string to search
              how are you
              Enter a character for which to search
              o
              No of Occurances : 2
              

              【讨论】:

                【解决方案9】:

                试试 indexOf() 方法。 它应该工作

                【讨论】:

                  【解决方案10】:

                  你的 Scanner 类在读取字符后没有移动到下一行

                  letter = in.next().charAt(0);
                  

                  在读取输入字符串之前添加另一个 in.nextLine()

                      System.out.println("Enter a character for which to search");
                      letter = in.next().charAt(0);
                      in.nextLine();
                      System.out.println("Enter the string to search");
                      sentence = in.nextLine();
                  

                  旧线程,但希望这会有所帮助:)

                  【讨论】:

                    猜你喜欢
                    • 2017-10-09
                    • 2010-11-12
                    • 2016-01-23
                    • 1970-01-01
                    • 2013-12-25
                    • 1970-01-01
                    • 2020-07-23
                    相关资源
                    最近更新 更多