简体   繁体   中英

Letter count in sentence not counting last word

I am new to java programming. This snippet calculates no of letters in each word and stores it as a string(excluding the spaces) but it is only calculating till "large" and not counting no of letters in "container".

class piSong
{
    String pi = "31415926535897932384626433833";
    public void isPiSong(String exp)
    {
        int i,count=0;
        String counter = "";
        String str;
        System.out.println(exp.charAt(25));
        for(i=0;i<exp.length()-1;i++)
        {
            if(Character.isWhitespace(exp.charAt(i)))
            {   str = Integer.toString(count);
                counter += str;
                count = 0;
                continue;
            }
            count++;

        }
        System.out.println(counter);
    }
}
public class isPiSong{
    public static void main(String[] args)
    {
        piSong p = new piSong();
        String exp = "can i have a large container";
        p.isPiSong(exp);
    }
} 

expected output:314157

current output: 31415

There are 2 things you should fix.

  1. In your for loop, your condition is i<exp.length()-1 . Why? You obviously want to include the last character also (which is charAt(exp.length() -1) ), so you condition should either be i <= exp.length() -1 or i < exp.length() .

  2. You logic is to count the letters whenever you encounter a whitespace. But after counting the last word, you dont have a whitespace. That's why it's not counting the last word.

To Fix, append count to counter after the loop.

// Loop ends here
counter += count;
System.out.println(counter);
String counter = "";
String[] array = exp.split(" ");
for(String s: array){
  counter += Integer.toString(s.length);
}

The second line splits the String into an array of strings (splits using each instance of a space in the String). The loop goes through each individual String in the array and adds its length to the counter String. It's preferable to use a StringBuilder instead of += to append to a String.

StringBuilder sb = new StringBuilder();
    String[] array = exp.split(" ");
    for(String s: array){
      sb.append(Integer.toString(s.length));
    }
String counter = sb.toString();

But both will do the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM