Java 计算字符串中字母的出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19580911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:31:07  来源:igfitidea点击:

Count the occurrences of a letter in a string

javafor-loop

提问by user2918429

I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This is a very basic code, and we have not gotten to arrays or much else yet. (I realize that I declared letter twice, but my brain is dead at this point) This is what I have tried so far and am having trouble with, any help is appreciated:

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

Ok I changed my code per suggestions, but now it is only reading the first word of my sentence?

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

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);

}
}

回答by Masudul

Your if (sentence.length() <= 0) {is not right. Change your condition like:

if (sentence.length() <= 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));

回答by Nizam

Try this:

尝试这个:

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);

回答by Paul Samsotha

Try this

尝试这个

forget String letter = ""<-- Delete
forget letter = in.next()<-- Delete

忘记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

回答by Karuppiah Subramaniyam

if (sentence.length() <= 0) {
            letter++;
}

The above part of code in your program is wrong. This will never be true until otherwise you input an empty string.

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

And basically this is not the correct logic. You will have to use the direct comparison.

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

回答by Francis

I see a couple of issues. First you have two variables with the same name.

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

Second your ifcondition check for the lenght of the sentence to be greater then 0 instead of checking for character equality.

其次,您的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));

I would also strongly suggest to validate the input (which is not done in the example above) instead of just assuming you got 1 character from the first input and 1 sentence in the second.

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

回答by alfasin

No need to loop:

无需循环:

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

OUTPUT:

输出:

numOfOccurences = 3

回答by MouseLearnJava

  1. You need to know the char you wanna search. You can use char charToSearch = letter.toCharArray()[0];
  2. Define a variable, such as countto count the occurrences of a letter in a given string.
  3. Loop the string and compare each char, if the char is equal to the char to search, then count++;
  1. 您需要知道要搜索的字符。您可以使用 char charToSearch = letter.toCharArray()[0];
  2. 定义一个变量,例如count来计算给定字符串中字母的出现次数。
  3. 循环字符串并比较每个字符,如果字符等于要搜索的字符,则count++;

Example--->

例子--->

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);

回答by Anto Robinson

Hope this will helpful to you.

希望这对你有帮助。

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);
    }
}

Sample Input Output:

样本输入输出

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

回答by Ameya Jadhav

try the indexOf() method. it should work

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

回答by Learnaholic

your Scanner class has not moved to the next line after reading the character

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

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

add another in.nextLine() before reading the input string

在读取输入字符串之前添加另一个 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();

old thread but hope this helps :)

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