Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Easy
  • Last Updated : 19 May, 2021

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

Input : geeks for geeks
Output :


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

  • 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 concatenation 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.



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];
            if (s.length() > 0)
                System.out.println(s + "->" + s.length());           
    public static void main(String[] args)
        String str = "geeks for geeks";





My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!