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?
You can use something like this:
String[] words = yourString.split(" ");
for (String word : words) {
System.out.println(word + " length is: " + word.length());
}
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.
Use an enhanced for loop and print out the word and its length.
foreach(String w : st.split()) {
System.out.println(w + ": " + w.length());
}