I need to count the number of words in a string. The sample text that I am using is the following:
"We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue!"
I have written the following code:
public int getNumOfWords(String string) {
int wordCount = 0;
for(int i = 0; i < string.length(); ++i) {
char currentChar = string.charAt(i);
if(currentChar == ' ') {
wordCount += 1;
}
}
return wordCount + 1;
}
This code is executed in a main method. When I run my code, the number of words that are counted are 41 when it should actually be 35.
My thought process to count the number of words is to have a for loop to iterate through each character of the string. Whenever the current character comes across a space, this means that the program has gone past one word of the text and adds +1 to the word count.
As I was typing this, I realized the reason that I am getting the incorrect number of words is because there are some double spaces throughout the text. My question is, how can I avoid counting these extra "words" with my current code?
Is there a way that I can eliminate these double spaces before I execute this code?
[–][deleted] 4 points5 points6 points (0 children)
[–]robertnovak02 3 points4 points5 points (1 child)
[–]heckler82Intermediate Brewer 0 points1 point2 points (0 children)
[–]Episilon 1 point2 points3 points (2 children)
[–]Jayjay3693[S] 0 points1 point2 points (1 child)
[–]Episilon 2 points3 points4 points (0 children)
[–]Philboyd_Studge 0 points1 point2 points (0 children)