如何查找字符串中的单词数-JAVA

问题描述:

如何在不使用Java循环的情况下找到字符串中的单词数?

How can to find the number of words in string without using loops in Java?

尝试一下.毫无疑问,这里绝对没有循环(假设String.length不进行迭代,String.substring不进行复制),甚至在幕后也没有,除非是在印刷过程中.

Try this. There are definitely no loops here (assuming String.length does not iterate and String.substring does not make a copy), not even behind the scenes, except in the printing of course.

  static int nSpaces ( String s ) {
    int n = 0;
    if ( s.length() > 0 ) {
      if ( s.length() > 1 ) {
        // Split it in half.
        int center = s.length() / 2;
        // Count each half.
        n += nSpaces(s.substring(0, center))
           + nSpaces(s.substring(center));
      } else {
        // Just 1 character.
        if ( s.charAt(0) == ' ' ) {
          // It's a space.
          n += 1;
        }
      }
    }
    //System.out.println(n+" spaces in '"+s+"'");
    return n;
  }

  static int nWords ( String s ) {
    return nSpaces (s) + 1;
  }

  public static void main(String args[]) {
    String test = "Now is the time for all good men to come to the aid of the party.";
    System.out.println("nWords(\""+test+"\") = "+nWords(test));
  }