Saturday, 8 June 2013

Java program to count number of words and letters

Code
--------
import java.util.Scanner;
import java.util.StringTokenizer;

class WordCount {
public static void main(String args[]) {
// Create Scanner object
Scanner s = new Scanner(System.in);

System.out.println("Please eneter a statement");
// Read a string
String st = s.nextLine();

// Split string with space
String words[] = st.trim().split(" ");

//way 1
System.out.println("No. of words " + words.length);

//way 2
System.out.println("No. of words " + new StringTokenizer(st).countTokens());

System.out.println("No. of letters " + st.length());

}
}


Sample output:
-------------------------------------------
Please eneter a statement
This is a test message entered by Admin
No. of words 8
No. of words 8
No. of letters 39



No comments:

Post a Comment