Write a java program to count words in a string : 

import java.util.Scanner;

public class CountWord {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence ");
String str = sc.nextLine();
int c=countWord(str);
System.out.println(c);

}

private static int countWord(String str) {
char ch[] = str.toCharArray();
int count=0;
for (int i = 0; i < ch.length; i++) {
if((i==0 && ch[i]!=' ' )|| (ch[i]!=' ' && ch[i-1]==' ')) {
count++;
}
}
return count;
}

}

Comments

Popular posts from this blog

program to calculate product of each column in matrix