how to count the letters in each letter in a strin

2019-06-14 20:43发布

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?

3条回答
乱世女痞
2楼-- · 2019-06-14 20:54

word.length() returns the length of a String.

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:

word.replaceAll("\p{Punct}", "").trim().length().

  • replaceAll("\p{Punct}", "") removes all punctuation marks from the String.

  • trim() removes all leading and trailing whitespaces.

So for example, a sentence:

I saw a will-o'-the-wisp.\n

(\n means the end of line character, which you might get if you read the String from a file, for example).

The sentence will split to:

"I"  
"saw"  
"a"  
"will-o'-the-wisp.\n"

the last string

will-o'-the-wisp.\n

has 18 characters, but that's more than the character count in the word. After the replaceAll() method, the string will look like:

willothewisp\n

and after the trim() method, the string will look like:

willothewisp

which has length 12, the length of the word.

查看更多
【Aperson】
3楼-- · 2019-06-14 21:04

Use an enhanced for loop and print out the word and its length.

foreach(String w : st.split()) {
    System.out.println(w + ": " + w.length());
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-06-14 21:13

You can use something like this:

String[] words = yourString.split(" ");

for (String word : words) {
  System.out.println(word + " length is: " + word.length());
}
查看更多
登录 后发表回答