how to count the exact number of words in a string that has empty spaces between words?

前端 未结 9 1768
猫巷女王i
猫巷女王i 2020-12-03 14:35

Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters

9条回答
  •  無奈伤痛
    2020-12-03 15:37

    public static int wordCount(String s){
        int counter=0;
        for(int i=0;i<=s.length()-1;i++){
            if(Character.isLetter(s.charAt(i))){
                counter++;
                for(;i<=s.length()-1;i++){
                    if(s.charAt(i)==' '){
                        i++;
                        break;
                    }
                }
            }
        }
        return counter;
    }
    

    This is what you need if don't use the predefined function. I have tested it by myself. Please let me know if there is any bugs!

提交回复
热议问题