Friday , July 21 2017
Home / java programs / Java Program To Count number of words in a String

Java Program To Count number of words in a String

Here we are going to write a program count the number of words in a string using Java.

Count the Number of words in a String :


import java.util.Scanner;

public class StringWordsCountExample {

    public static void main(String a[]) {

        int count = 0;
        Scanner s1 = new Scanner(System.in);
        System.out.println("Enter a String : ");
        String inputValue = s1.nextLine();

        if (inputValue != null && !inputValue.equals("")) {

            int length = inputValue.length();

            char[] findCharctersArray = new char[length];

            for (int k = 0; k < length; k++) {
                findCharctersArray[k] = inputValue.charAt(k);
                if (((k > 0) && (findCharctersArray[k] != ' ') && (findCharctersArray[k - 1] == ' '))
                        || ((findCharctersArray[0] != ' ') && (k == 0)))
                    count++;
            }
            System.out.println("The number of words in input String : " + count);
        }

    }
}

Output :

Enter a String : online tutorials point
The number of words in input String : 3

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java program to find sum of digits

In this Java programming tutorials, I am going to show you how to calculate sum …

Leave a Reply

Your email address will not be published. Required fields are marked *