gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:47:29 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com