Java Beginner - Counting number of words in sentence

后端 未结 17 1675
忘了有多久
忘了有多久 2021-01-01 05:29

I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn\'t work. No matter what I write, I on

17条回答
  •  伪装坚强ぢ
    2021-01-01 05:53

    Tested method - handles all inputs

    public static void countwords() {
        String s = "  t    ";
        int count = 0;
        int length = s.length()-1;
        char prev = ' ';
    
        for(int i=length; i>=0; i--) {
            char c = s.charAt(i);
            if(c != prev && prev == ' ') {
                count++;
            }
            prev = c;
        }
        System.out.println(count);
    }
    

提交回复
热议问题