如何查找字符串中的单词数-JAVA [英] How to find the number of words in string - JAVA

查看:187
本文介绍了如何查找字符串中的单词数-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));
  }

这篇关于如何查找字符串中的单词数-JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆