+ 2
How to split symbols in a string (java)
I have a task to count how many words are in a string. So I created a string[] variable_name = string.split(" ") ; And then used a for loop to count how many words are. And I was thinking, what if the user won't put white space at the end of sentence or after using comma, brackets etc... What should I do in order make my program to count the number of words in this case?
8 ответов
+ 1
still there is something between words or something that is not words, isn't it?
+ 1
I was thinking of making one more loop in order to take each word and to split it by using regex( "[!?,. :+]"), but I just make my code more complicated. So I wonder if there is a easier solution
+ 1
Your task should have explained clearly for what you can count it as word & how it is separated by if there is nothing specifically mentioned then just simply go with white space that would be fine i think Zotta
+ 1
Martin Taylor yeah, I was thinking about it to, I just wanted to know if there is a easy way for my self. Thanks for your answer and if is still possible, can you take a look on another question of mine https://www.sololearn.com/Discuss/2906549/?ref=app
+ 1
String str = """
I learn Java. He learns python.
I learn Java.He learns python.""";
String[] aStr = str.split("\\W+");
System.out.println( aStr.length ); //12
// if word is a-zA-Z_0-9
0
"can’t" for cannot is counted as one word, but "it's" as two :)