计算字符串中的字母 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19163876/
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 14:38:38  来源:igfitidea点击:

Count letters in a string Java

javaarrays

提问by user2843446

I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total.I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.

我正在做一个作业,我必须编写一个程序来读取用户的字符串并打印出字符串中出现次数的字母。例如“Hello world”,它应该打印出“h=1 e=1 l=3 o=2 ...等”,但我的只写“hello world”和字母总数。我不能使用 hashmap 函数,只能使用数组。有人可以就如何从下面的书面代码继续获得我喜欢的功能给我一两个提示吗?我不明白如何将书面输入保存在数组中。

Here's my code so far.

到目前为止,这是我的代码。

public class CountLetters {
    public static void main( String[] args ) {
        String input = JOptionPane.showInputDialog("Write a sentence." );
        int amount = 0;
        String output = "Amount of letters:\n";

        for ( int i = 0; i < input.length(); i++ ) {
            char letter = input.charAt(i);
            amount++;
            output = input;
        }
        output += "\n" + amount;
        JOptionPane.showMessageDialog( null, output,
                             "Letters", JOptionPane.PLAIN_MESSAGE ); 
    }
}

采纳答案by Masudul

You don't need 26 switchcases. Just use simple code to count letter:

你不需要26switch箱。只需使用简单的代码来计算字母:

    String input = userInput.toLowerCase();// Make your input toLowerCase.
    int[] alphabetArray = new int[26];
    for ( int i = 0; i < input.length(); i++ ) {
         char ch=  input.charAt(i);
         int value = (int) ch;
         if (value >= 97 && value <= 122){
         alphabetArray[ch-'a']++;
        }
    }

After done count operation, than show your result as:

完成计数操作后,将结果显示为:

 for (int i = 0; i < alphabetArray.length; i++) {
      if(alphabetArray[i]>0){
        char ch = (char) (i+97);
        System.out.println(ch +"  : "+alphabetArray[i]);   //Show the result.
      }         
 }

回答by Colin D

  • Create an integer array of length 26.
  • Iterate each character of the string, incrementing the value stored in the array associated with each character.
  • The index in the array for each character is calculated by x - 'a'for lower case characters and x - 'A'for upper case characters, where xis the particular character.
  • 创建一个长度为 26 的整数数组。
  • 迭代字符串的每个字符,递增存储在与每个字符关联的数组中的值。
  • 数组中每个字符的索引由x - 'a'小写字符和x - 'A'大写字符计算,其中x是特定字符。

回答by FazoM

You can create an Array which first element will represent 'a', second 'b', etc. If you need distinction between lower and upper cases than you can add it at the end. This array will have all values equals 0 at the beginning. Then you iterate through your sentence and you increment required values on the array. At the end you print all values that are > 0. Simple?

您可以创建一个数组,其中第一个元素将代表“a”、第二个“b”等。如果您需要区分大小写,则可以在末尾添加它。这个数组的所有值在开始时都等于 0。然后你遍历你的句子并增加数组上所需的值。最后打印所有 > 0 的值。简单吗?

Let me know if you need more help

如果您需要更多帮助,请告诉我

回答by Tobias Kremer

No you should not create an array of 26. This will break if the string contains unexpected characters. (?, ?, ü anyone?) As I pointed out im my comment use a Map. This will work forr all posible characters out there.

不,你不应该创建一个 26 的数组。如果字符串包含意外的字符,这将中断。(?, ?, ü 任何人?) 正如我指出的,我的评论使用地图。这将适用于所有可能的字符。

回答by Hemanth Thati

import java.io.*;

导入 java.io.*;

public class CharCount {

公共类 CharCount {

public static void main(String[] args) throws IOException
{
    int i,j=0,repeat=0;
    String output="",input;
    char c=' ';
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("enter name ");
    input=br.readLine();
    System.out.println("entered String ->\""+input+"\"");
    input=input.toLowerCase();

    for(i=0;i<input.length();i++)
    {
        for(j=0;j<output.length();j++)
        {
            if(input.charAt(i)==output.charAt(j) || input.charAt(i)==c)
            {
                repeat=1;
                break;
            }
        }
        if(repeat!=1)
        {
            output=output+input.charAt(i);
        }
        repeat=0;
    }

    System.out.println("non-reepeated chars in name ->\""+output+"\"");

    int count[]=new int[output.length()];
    for(i=0;i<output.length();i++)
    {
        for(j=0;j<input.length();j++)
        {
            if(output.charAt(i)==input.charAt(j))
                count[i]=count[i]+1;
        }
    }
    for(i=0;i<output.length();i++)
        System.out.println(output.charAt(i)+"- "+count[i]);
}

}

}