Here we are going to write a program count the number of words in a string using Java.
Count the Number of words in a String :
[java]
import java.util.Scanner;
public class StringWordsCountExample {
public static void main(String a[]) {
int count = 0;
Scanner s1 = new Scanner(System.in);
System.out.println("Enter a String : ");
String inputValue = s1.nextLine();
if (inputValue != null && !inputValue.equals("")) {
int length = inputValue.length();
char[] findCharctersArray = new char[length];
for (int k = 0; k < length; k++) {
findCharctersArray[k] = inputValue.charAt(k);
if (((k > 0) && (findCharctersArray[k] != ‘ ‘) && (findCharctersArray[k – 1] == ‘ ‘))
|| ((findCharctersArray[0] != ‘ ‘) && (k == 0)))
count++;
}
System.out.println("The number of words in input String : " + count);
}
}
}
[/java]
Output :
Enter a String : online tutorials point The number of words in input String : 3
Happy Learning 🙂