Untitled
unknown
plain_text
9 months ago
1.3 kB
16
Indexable
package STRINGS;
import java.util.Scanner;
public class CountNoOfWords {
/**
*This Class Takes a string s consisting of words and spaces, return the number of words in the string.
* A word is defined as a sequence of non-space characters separated by at least one space.
*
* Examples:
* Input: s = "Take you forward"
* Output: 3
* Explanation: The string has 3 words separated by spaces.
*
* Input: s = " Hello World "
* Output: 2
* Explanation: Multiple spaces between and around words are ignored.
*/
public static int countNoOFWords(String s){
int wordcount = 0;
boolean isWord = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ') {
if (!isWord) {
wordcount++;
isWord = true;
}
} else {
isWord = false;
}
}
return wordcount;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("ENTER A STRING - ");
String str = s.nextLine();
System.out.print("NO OF WORDS IN A STRING -> " + countNoOFWords(str));
}
}
Editor is loading...
Leave a Comment