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?
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 doingword.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:
(
\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:
the last string
has 18 characters, but that's more than the character count in the word. After the
replaceAll()
method, the string will look like:and after the
trim()
method, the string will look like:which has length 12, the length of the word.
Use an enhanced for loop and print out the word and its length.
You can use something like this: