JavaAlgorithms/countwords.java

19 lines
508 B
Java
Raw Normal View History

2017-04-09 12:56:56 +08:00
import java.util.Scanner;
2017-04-08 20:56:06 +08:00
class CountTheWords
{
2017-04-09 12:56:56 +08:00
public static void main(String args[])
2017-04-08 20:56:06 +08:00
{
System.out.println("Enter the string");
Scanner sc = new Scanner(System.in);
String s=sc.nextLine();
2017-04-09 12:56:56 +08:00
int count = 1;
for (int i = 0; i < s.length()-1; i++)
2017-04-08 20:56:06 +08:00
{
if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
{
2017-04-09 12:56:56 +08:00
count++;
2017-04-08 20:56:06 +08:00
}
}
2017-04-09 12:56:56 +08:00
System.out.println("Number of words in the string = "+count);
2017-04-08 20:56:06 +08:00
}
}