+ 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?

18th Oct 2021, 4:34 PM
Zotta
Zotta - avatar
7 Respostas
+ 1
still there is something between words or something that is not words, isn't it?
18th Oct 2021, 6:33 PM
zemiak
+ 1
zemiak I will write down an example I learn Java. He learns python. Output : 6 words I learn Java.He learns python. Output 5 words As you can see, my code reads Java.He as one word because there is no space
18th Oct 2021, 7:00 PM
Zotta
Zotta - avatar
+ 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
18th Oct 2021, 7:04 PM
Zotta
Zotta - avatar
+ 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
18th Oct 2021, 7:17 PM
Adithya Keshav T
Adithya Keshav T - avatar
+ 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
18th Oct 2021, 7:47 PM
Zotta
Zotta - avatar
+ 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
18th Oct 2021, 7:48 PM
zemiak
0
"can’t" for cannot is counted as one word, but "it's" as two :)
18th Oct 2021, 8:16 PM
zemiak