Open In App

Java program to count the characters in each word in a given sentence

Write a Java program to count the characters in each word in a given sentence?

Examples: 



Input : geeks for geeks
Output :
geeks->5
for->3
geeks->5

Approach:Here we have to find out number of words in a sentence and the corresponding character count of each word. 



Implementation:




class CountCharacterInEachWords {
    static void count(String str)
    {
        // Create an char array of given String
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
 
            // Declare an String with empty initialization
            String s = "";
 
            // When the character is not space
            while (i < ch.length && ch[i] != ' ') {
 
                // concat with the declared String
                s = s + ch[i];
                i++;
            }
 
            if (s.length() > 0)
                System.out.println(s + "->" + s.length());           
        }
    }
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        count(str);
    }
}

Output
geeks->5
for->3
geeks->5

Time Complexity: O(|S|).
Auxiliary Space: O(|S|), where |S| is the length of the input string.

Approach:  Using  split( ) and temp array

Steps involved: 

Note : Sometimes split() function won’t work properly when splitting should be done based on some regular expressions like

OR sign (|)
question mark (?)
asterisk (*)
plus sign (+)
backslash (\)
period (.)
caret (^)
square brackets ([ and ])
dollar sign ($)
ampersand (&) 

We need to specify them as split(“\\(split char)”) where (split char) would be one of the character from the above regular expression.

Below is the implementation of the above approach.




/*package whatever //do not write package name here */
 
import java.util.*;
class GFG {
    public static void main(String[] args) {
         
        String s="Geeks   For Geeks";
        count(s);
         
    }
    public static void count(String s)
    {
        //split method splitting the string
        // based on a space
        String[] temp=s.split("\\ ");
         
        for(String t: temp)
        {
            // checking whether the word is not empty
            if(t.length()>0)
            System.out.println(t+" -> "+t.length());
        }
    }
}
//This code is contributed by aeroabrar_31

Output
Geeks -> 5
For -> 3
Geeks -> 5

Time Complexity: O(|S|).
Auxiliary Space: O(|S|), where |S| is the length of the input string.


Article Tags :