Answers for "count number of words in word"

1

Count number of words in a String

public static void main (String[] args) {

     System.out.println("Simple Java Word Count Program");

     String str1 = "Today is Holdiay Day";

     String[] wordArray = str1.trim().split("\\s+");
     int wordCount = wordArray.length;

     System.out.println("Word count is = " + wordCount);
}
Posted by: Guest on August-14-2021
0

Count how many times a word can be made

/* Java program to count no of words
from given input string. */
public class GFG {
  
    static final int OUT = 0;
    static final int IN = 1;
      
    // returns number of words in str
    static int countWords(String str)
    {
        int state = OUT;
        int wc = 0;  // word count
        int i = 0;
         
        // Scan all characters one by one
        while (i < str.length())
        {
            // If next character is a separator, set the
            // state as OUT
            if (str.charAt(i) == ' ' || str.charAt(i) == '\n'
                    || str.charAt(i) == '\t')
                state = OUT;
                 
      
            // If next character is not a word separator
            // and state is OUT, then set the state as IN
            // and increment word count
            else if (state == OUT)
            {
                state = IN;
                ++wc;
            }
      
            // Move to next character
            ++i;
        }
        return wc;
    }
      
    // Driver program to test above functions
    public static void main(String args[])
    {
        String str = "One two       three\n four\tfive  ";
        System.out.println("No of words : " + countWords(str));
    }
}
// This code is contributed by Sumit Ghosh
Posted by: Guest on March-23-2022

Code answers related to "count number of words in word"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language