繁体   English   中英

如何从用户输入的字符串句子中获取最大出现字符及其出现次数?

[英]How to get the maximum occurring character and its occurrences from a user inputted String sentence?

我有一个程序要求用户输入一个字符串句子和 output 它的最大出现字符及其出现次数。

我这里的问题是,计算最大字符及其出现次数的 function 只计算单个单词(全部小写)的最大字符及其出现次数,而不是完整的句子或以大写字母开头的单词。

如果用户输入一个句子,程序在 freqLetter 数组(频繁字母数组)中一直有一个索引越界,我不知道为什么它会越界,它与句子? 我应该在迭代数组时创建另一个循环还是应该创建另一个数组?? (我有时在操作数组索引时感到困惑)。

代码:

static void maxOccuringChar(char str[]) {    // function that counts that max character and its occurences
    char maxChar = ' ';

    int freqLetter[] = new int[26];
    int lengthString = str.length;
    int maximum = -1;


    for (int i = 0; i < lengthString; i++)
        freqLetter[str[i] - 'a']++;    // I'm not sure why it becomes out of bounds for some reason


    for (int i = 0; i < 26; i++)
        if (maximum < freqLetter[i]) {
            maximum = freqLetter[i];
            maxChar = (char)(i + 'a');
        }

    System.out.print(maxChar + " = " + maximum); // returns result    
}

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

    char[] StringInput = in.nextLine().toCharArray();   // user inputs the given String sentence and puts into character array

    maxOccuringChar(StringInput);  // calls function and returns the maximum character and and its occurences
}
Output 1:
Elephant
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -28 out of bounds 
for length 26

Output 2:
I am confused
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -24 out of bounds 
for length 26

Output 3:     // works fine here
hello
l = 2
Process finished with exit code 0

非常感谢您的回复,并且确实会在这方面帮助我!

非常感谢大家!!!

出现问题是因为空格代码是 32。将循环更改为跳过空格

for (int i = 0; i < lengthString; i++) {
    if(str[i] == ' ') {
        continue;
    }
    freqLetter[str[i] - 'a']++;
}

ASCII 表

您也可以使用streams解决此问题

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

    String input = in.nextLine();

    System.out.println(input.chars()
            .mapToObj(x -> (char) x)
            .collect(Collectors.groupingBy(x -> x, Collectors.counting()))
            .entrySet()
            .stream()
            .max(Comparator.comparingLong(Map.Entry::getValue))
            .get());
}

Output:

123333
3=4

但它也会计算空格。 如果您不想,则在mapToObj(...)之后添加此行

.filter(c -> c != ' ')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM