+ 5

[Technical question]

I need an algorithm to count the number of words in string regardless of spaces between them. example: String s="this is an example"; *note: I tried an algorithm and it worked, but only in some cases, and now trying to get some more ideas.

2nd Apr 2017, 5:17 PM
Hsn
Hsn - avatar
7 Answers
+ 3
This is my code, try to change spaces and words in the string. Need some suggestions! https://code.sololearn.com/cPfdG8b7yapN/?ref=app
2nd Apr 2017, 6:26 PM
Hsn
Hsn - avatar
+ 4
Here is an option: Read every char in the string define a wordReading mode enter wordReading mode on first char that is not a space. exit wordReading mode on first space store the word found and increase the number of found words upon exiting wordReading mode. use the number of found words to create an array and store extracted substrings. I'd go for the suggested regex solution. regex solution
2nd Apr 2017, 10:34 PM
seamiki
seamiki - avatar
+ 3
i would look into regular expressions. You could do something like split the string into an array I believe its String[] array = s.split ("\\s+"); and then just do array.length for the number of words
2nd Apr 2017, 5:31 PM
Edward
+ 3
@Edward thanks, but I'm looking for a manual way to do that 😃 Besides, this will take only the first space, nothing different than split on single space.
2nd Apr 2017, 5:46 PM
Hsn
Hsn - avatar
+ 3
@seamiki thanks for your efforts, this is the same approach I used, except of storing in the array . although I know it can be solved using regex, but I needed to do it manually using loops ..
3rd Apr 2017, 7:33 AM
Hsn
Hsn - avatar
+ 1
there is your code . ping me whenever you copy the code so I can. delete it. https://code.sololearn.com/c4Ja53jX5tUn/?ref=app
2nd Apr 2017, 6:49 PM
Keshave Jat
Keshave Jat - avatar
0
if you don't have any problem with regex then you can use regex for the task
2nd Apr 2017, 6:26 PM
Keshave Jat
Keshave Jat - avatar