如何计算字符串中每个字母的出现次数?

时间:2013-03-07 16:56:10

标签: java string

我不确定如何计算每个字母的出现次数。有人能指出我这样做的正确方向,谢谢你:)

if(icanreadstrings.equals ("start")){ 

            String strten = Console.readLine("Enter 10 letters (no spaces,commas between each letter and no numbers): "); // Asks the user to enter 10 letters which is then saved as a string "strten".
            Console.println(strten);// Prints out whatever the user entered.

            if(strten.matches("[a-zA-Z]+") && strten.length() == 10){ // if whatever the user enters is letters (not numbers) and if it matches to the length, which is 10.
                Console.println("There are " + strten.length() + " letters that you've wrote."); // lets the user continue if they've wrote 10 letters, yes 10!

            }else{
                Console.println("There are more than or less than 10 letters that you've wrote or you have numbers in your list of letters. Please rewrite 10 different LETTERS for this program to continue."); // Checks to see if you wrote more than  10 letters if you did then it prompts a message and the user can't continue until he writes 10 letters.
                }


         }

1 个答案:

答案 0 :(得分:1)

使用Map<Character, Integer>,然后遍历字符串。在第一次出现角色时,将角色和1放在地图中。在随后的所有事件中,将一个添加到地图中已存在的该字符的值。

然后,地图的条目集将为您提供您所追踪的数据。