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.



  • Here first we create an equivalent char array of given String.
  • Now we iterate the char array using for loop. Inside for loop we declare a String with empty implementation.
  • Whenever we found an alphabet we will perform concatination of that alphabet with the String variable and increment the value of i.
  • Now when i reaches to a space it will come out from the while loop and now String variable has the word which is previous of space.
  • Now we will print the String variable with the length of the String.
filter_none

edit
close

play_arrow

link
brightness_4
code

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);
    }
}

chevron_right


Output:

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

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.