JavaAlgorithms/countwords.java

33 lines
746 B
Java
Raw Normal View History

2017-04-09 12:56:56 +08:00
import java.util.Scanner;
/**
* You enter a string into this program, and it will return how
* many words were in that particular string
*
* @author Unknown
*
*/
2017-04-08 20:56:06 +08:00
class CountTheWords
{
/**
* The main method
*
* @param args Command line arguments
*/
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);
sc.close();
2017-04-08 20:56:06 +08:00
}
}