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

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

    If you want to ignore leading, trailing and duplicate spaces you can use

    String trimmed = text.trim();
    int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
    

提交回复
热议问题