Write the countWords method that returns the number of “words” in the text, wher
ID: 3820942 • Letter: W
Question
Write the countWords method that returns the number of “words” in the text, where a “word” as any string separated by one space (you are not expected to handle multiple spaces between words). For example:
countWords( "Along came a spider and sat down beside her")
returns 9 because nine “words” appeared in the text. Note the following:
• Your method returns 0 if presented with the empty string;
• You may use only the String methods used in class: charAt( int ), indexOf( char)
and/or length();
• Assume that text does not begin nor does it end with any spaces; spaces appear only between words;
• Your method can use at most one Java iteration statement (either a for, a while
or a do-while statement); and • Your method may go through the text only once.
static int countWords( String text ) { String space = " "; int wordCount = 0;
Explanation / Answer
Source code:
static int countWords(String text){
String space=" ";
int wordCount=0;
if(text.length()==0) return 0;
for(int i=0;i<text.length();i++){
//Comparing the character of string with space . If equal incements.
if(text.charAt(i)==space.charAt(0)){
++wordCount;
}
}
return wordCount+1;
}
Output :
The countWords() takes the string whatever we pass as a parameter . If string is empty ,it returns 0(zero) otherwise it counts the number of words by incrementing the variable wordCount value with 1 .Upto now we counted the number of spaces but actually no of words=no of spaces+1 . So countWords() returns wordCount+1.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.