program to count words in a given string

The aim of this article is to write Java programs that count words in a given string.

  • Declare a string.
  • Create the char object and pass inside string data.
  • To counts the words present in the string, we will iterate through the string.
  • Define one if condition and count the spaces present in the string. As each word always ends with a space.
  • If a string starts with a space, then we must not count the first space as it is not preceded by a word.
  • To count the last word, we will increment the count by 1.
				
					public class WordCount {
	public static void main(String[] args) {
		String s = "java spring";
		int count = 0;
		char ch[] = new char[s.length()];
		for (int i = 0; i < s.length(); i++) {
			ch[i] = s.charAt(i);
			if ((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' ') || ((ch[0] != ' ') && (i == 0))) {
				count++;
			}
		}
		System.out.println("Total number of word:- " + count);
	}
}
				
			

output :-
Total number of word:- 2