java 如何在Java中计算字符串中每个字母中的字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15317778/
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
how to count the letters in each letter in a string in Java?
提问by user2105467
I have used this code to try this out:
我已使用此代码进行了尝试:
String st="Hello world have a nice day";
String arr=st.Split(" ");
for (int i=0; i < arr.length; i++) {
???
}
But it doesn't work.
但它不起作用。
I want it to output something like this:
我希望它输出这样的东西:
Hello=5
World=5
have=4
a=1
nice=4
day=3
Does anyone know the right code, please?
请问有人知道正确的代码吗?
回答by BloodShura
You can use something like this:
你可以使用这样的东西:
String[] words = yourString.split(" ");
for (String word : words) {
System.out.println(word + " length is: " + word.length());
}
回答by Jakub Zaverka
word.length()
returns the length of a String.
word.length()
返回字符串的长度。
However, the split()
method will just split the String by spaces, leaving everything in the resulting splits. By everything I mean punctuation, tabulators, newline characters, etc, and all those will be counted towards the length. So instead of just doing word.length()
, you might want to do something like:
但是,该split()
方法只会按空格拆分字符串,而将所有内容保留在结果拆分中。我的意思是标点符号、制表符、换行符等,所有这些都将计入长度。因此word.length()
,您可能想要执行以下操作,而不仅仅是执行:
word.replaceAll("\p{Punct}", "").trim().length()
.
word.replaceAll("\p{Punct}", "").trim().length()
.
replaceAll("\p{Punct}", "")
removes all punctuation marks from the String.trim()
removes all leading and trailing whitespaces.
replaceAll("\p{Punct}", "")
从字符串中删除所有标点符号。trim()
删除所有前导和尾随空格。
So for example, a sentence:
例如,一个句子:
I saw a will-o'-the-wisp.\n
我看到了一个鬼火。\n
(\n
means the end of line character, which you might get if you read the String from a file, for example).
(\n
表示行尾字符,例如,如果您从文件中读取字符串,则可能会得到该字符)。
The sentence will split to:
句子将拆分为:
"I"
"saw"
"a"
"will-o'-the-wisp.\n"
the last string
最后一个字符串
will-o'-the-wisp.\n
鬼火。\n
has 18 characters, but that's more than the character count in the word. After the replaceAll()
method, the string will look like:
有 18 个字符,但这比单词中的字符数还多。在该replaceAll()
方法之后,字符串将如下所示:
willothewisp\n
柳树\n
and after the trim()
method, the string will look like:
在trim()
方法之后,字符串将如下所示:
willothewisp
柳树
which has length 12, the length of the word.
其中长度为 12,即单词的长度。
回答by Makoto
Use an enhanced for loop and print out the word and its length.
使用增强的 for 循环并打印出单词及其长度。
foreach(String w : st.split()) {
System.out.println(w + ": " + w.length());
}