How to count letter of each word

17,324

Solution 1

Step 1 - Find the number of words in the sentence using the space separator.

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

Step 2 - Find letter count in each word.

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

// Print sResultString 

Solution 2

Take a look at http://www.tutorialspoint.com/java/java_string_split.htm. You should be able to use the Java String.split() function to break up the string by spaces " ". That should give you an array that contains each word. Then it is simply finding the length of each word.

Share:
17,324
amirhossein Nezamlou
Author by

amirhossein Nezamlou

Updated on June 27, 2022

Comments

  • amirhossein Nezamlou
    amirhossein Nezamlou almost 2 years

    I was wondering how I would write a method to count the number of words and number of each word letters for example if input is "The Blue Sky" in return i take something that show me there was 3 words 3 letter 4 letter 3 letter

    i'v found this code already

    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 really appreciate any help I can get! Thanks!