简体   繁体   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;
  }

Example output for this would be: 输出示例如下:

numberOfWords("Hello whats up?")
3 word

This would work for all proper sentences but I have to account for bad input for example: 这适用于所有适当的句子,但我必须考虑输入错误的情况,例如:

"Hi             my         name      is bob"

, this would be like thirty plus words. ,这将是三十多个单词。 Also

"                 "

, should be 0 words. ,应为0个字。 Is there any simple way to make the first example to "hi my name is bob" ? 有没有简单的方法可以使第一个示例成为“嗨,我叫鲍勃”?

you can do something like this : 您可以执行以下操作

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

or (simplest way): 或(最简单的方法):

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

Simplest will work in every case 最简单的方法在每种情况下都适用

        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