java - 将字符串中字母的出现次数计数到 26 的 int 数组中

标签 java arrays string letters find-occurrences

我需要获取多行文本并计算每行中每个字母的出现次数。最后一行必须以句点结束。我被要求创建一个长度为 26 的 int 数组,其中 arrayName[0] = number of a's , arrayName[1] = number of b's等,并且需要忽略该字母大小写。我无法检查每个字母的出现次数并定义具有正确出现次数的索引变量。到目前为止我的代码:

import java.util.Scanner;

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

    String[] textBlock = new String[10];

    System.out.println("Enter text.");
    int index;
    //Allows me to type in something for all "lines" of text until I end one with a period.
    for(index = 0; index < textBlock.length; index++)
    {
        textBlock[index] = input.nextLine();

        if(textBlock[index].contains("."))
        {
            System.out.println("Period found");
            break;
        }
    }
    //Outputs what the user printed except for the lines not typed in (they return null).
    System.out.println("Text input by user:");
    for(index = 0; index < textBlock.length; index++)
    {
        if(textBlock[index] != null)
        {
            System.out.println(textBlock[index]);
        }
    }
    //int array
    int[] occurrences = new int[26];

    //used to turn letter into number
    char letter = 'a' - 49;
    char letter2 = 'b' - 49;
    char letter3 = 'c' - 49;

    //checks that numbers are correct (return "0" for a, "1" for b, and "2" for c)
    System.out.println("Number value of a: " + letter);
    System.out.println("Number value of b: " + letter2);
    System.out.println("Number value of c: " + letter3);

}// End of main
}//End of program

最佳答案

统计每一行的字符出现次数。然后打印它们。试试这个...

//final int SIZE = 1000;
//String[] textBlock = new String[SIZE];

Scanner in = new Scanner(System.in);
String line;

//frequency array for storing which Character is occurs how many times
int[] frequencyArray = new int[26];
Arrays.fill(frequencyArray, 0);

System.out.println("Enter text : ");

// take input un-till find the (.) in a line
// and also count the frequency of Character of current line
while (true) {
    line = in.nextLine();
    for (int i = 0; i < line.length(); i++) {
        char ch = Character.toLowerCase(line.charAt(i));
        if (Character.isLetter(ch)) {
            frequencyArray[ch - 'a']++;
        }
    }
    if (line.contains(".")) {
        break;
    }
}

for (int i = 0; i < 26; i++) {
    System.out.println("Total Number of " + (char)(i + 'a') + " : " + frequencyArray[i]);
}

关于java - 将字符串中字母的出现次数计数到 26 的 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825558/

相关文章:

c++ - 如何在 C++ 中获取指向 char[] 的指针的内存地址

java - 我真的很难弄清楚如何让我的 GUI 窗口显示数组中的值

java - 从 Java 结果集中读取 Unicode 文本

java - Jersey 2.22 : How do I retrieve the URL (with QueryParams) from WebTarget?

java - 用实际 Controller 替换模拟的 Spring Boot Controller

javascript - 检查一个元素是否存在于对象数组中

c++ string.find() 返回字符串的长度

c - 如何多次打印一个字符串而仅引用它一次?

c - C 中的字符串常量和数组

java - 检查 Firebase 数据库中存在的所有节点中的特定值