How to Count Words in a String in Java

This is the simple java program that counts the number of words in a string. Java has many builtin functions for strings but you can also do it with your own simple logic.

Source Code   


package packaga.sixteen;
/**
 *
 * @author Shan
 */
public class countWords {

/**
     * @param args the command line arguments
     */
public static void main(String[] args) {
String str="Quick brown fox jumps over the lazy dog";
String arr[]=str.split(" "); // split the sentence in an array of words
System.out.println("Words List:");
for ( int i = 0 ; i < arr.length ; i++ ) {
System.out.println(arr[i]);
}
System.out.println("");
System.out.print("Words Count: ");
System.out.println(""+arr.length); // displays the counts
}
}

Output of the Program


Count Words in a String in Java



Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment