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

前端 未结 9 1789
猫巷女王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:26

    public static int wordCount(String s){
        if (s == null)
           return 0;
        return s.trim().split("\\s+").length;
    }
    

    Have fun with the function.

提交回复
热议问题