Java – How to count the letters of each word

How to count the letters of each word… here is a solution to the problem.

How to count the letters of each word

I would like to know how to write a method to count the number of words and the number of letters per word
For example, if the input is “The Blue Sky” as a return, I will take something and tell me that there are 3 words 3 letters 4 letters 3 letters

I have found this code

public static int countWords(String s){

int wordCount = 0;

boolean word = false;
    int endOfLine = s.length() - 1;

for (int i = 0; i < s.length(); i++) {
         if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
             if char isn't a letter and there have been letters before,
             counter goes up.
        } else if (! Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
             last word of String; if it doesn't end with a non letter, it
             wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

I would really appreciate any help I could get! Thanks!

Solution

Step 1 – Count the number of words in a sentence using a space separator.

 String CurrentString = "How Are You";
    String[] separated = CurrentString.split(" ");
    String sResultString="";
    int iWordCount = separated.length;
    sResultString = iWordCount +" words";

Step 2 – Count the number of letters in each word.

    for(int i=0; i<separated.length; i++)
    {
    String s = separated[i];
    sResultString = sResultString + s.length + " letters ";
    }

 Print sResultString 

Related Problems and Solutions