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

标签 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.
                }


         }

最佳答案

使用 Map<Character, Integer> ,并循环遍历字符串。当字符第一次出现时,将字符和 1 放入 map 中。在所有后续出现的情况下,为 map 中已有的该角色的值加一。

map 的条目集将为您提供所需的数据。

关于java - 如何计算字符串中每个字母出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277112/

相关文章:

java - 无法在 IntelliJ 中构建 Spring RestService 教程

c++ - const char* 是指向单个字符还是字符串?

java - 字符串操作Java搜索子字符串序列

复制列名并拼接

java - 为什么 tomcat 无法启动无法启动 apache tomcat web 服务器 tomcat.service : Control process exited, code=exited status=203

java - 什么会导致次要 GC 时间和总暂停时间之间存在较大差异?

c++ - 在 C++ 中使用 if(cin>>) 命令

c - 查找 C 语言中最长的单词

java - 如何上传带有 Google Drive REST API v2 链接的文件

java - JTextComponent.print();打印空白