繁体   English   中英

查找句子中单词数的简单Java程序

[英]Simple java program that finds the number of words in a sentence

  public static String number(String words) {
      int length = words.length;
      int total = 0;
      while(int index < length) {
          total = total + 1;
          index = index + 1;
          }
      }
      String output;
      output = total + " word";
      return output;
  }

输出示例如下:

numberOfWords("Hello whats up?")
3 word

这适用于所有适当的句子,但我必须考虑输入错误的情况,例如:

"Hi             my         name      is bob"

,这将是三十多个单词。

"                 "

,应为0个字。 有没有简单的方法可以使第一个示例成为“嗨,我叫鲍勃”?

您可以执行以下操作

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

或(最简单的方法):

use str.replaceAll("\\s+"," "); 

最简单的方法在每种情况下都适用

        String word = "Hi             my         name      is bob";
        word = word.replaceAll("\\s+", " ");
        String count [] = word.split(" ");

        System.out.println(count.length);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM