写一个方法来返回字符串中的单词数量?编辑

时间:2015-10-17 02:03:43

标签: java

编写一个名为wordCount的方法,该方法接受String作为其参数,并返回String中的字数。单词是一个或多个非空格字符的序列(除了''之外的任何字符)。例如,调用wordCount(" hello")应该返回1,调用wordCount("你好吗?")应该返回3,调用wordCount(" this string有宽空格")应该返回5,而调用wordCount("")应该返回0。

好吧所以我的问题是当程序输入的字符串/短语单词开始时 如果没有空格而不是单词,则不会在句子中注册以下单词并返回值1.

所以如果wordCount是("这个字符串有宽的空格") 应该返回5,但只退休0.我不明白为什么你能帮我理解我搞砸了哪里?

这是我的方法:

   public static int wordCount(String s) {
          int word = 0;
          if(s!=null)
          if(s.charAt(0)!=' ') {
              word++;
          }
          for(int i=0; i<=s.length(); i++) 
          {
          if(s.charAt(i)!=' ' && s.charAt(i+1) ==' ') 
          {
                word++;
          }
              return word;
        }
           return word;
    }

2 个答案:

答案 0 :(得分:0)

 public static int wordCount(String s) {
     if(s!=null)
       return s.trim().split(" ").length ;
     return 0;
}

答案 1 :(得分:0)

我首先要定义完成。通常,那就是你的功能定义完成的时候。一个这样的例子(来自你的问题)可能看起来像

public static void main(String[] args) {
    String[] inputs = { "hello", "how are you?",
            " this string has wide spaces ", " " };
    int[] outputs = { 1, 3, 5, 0 };
    String[] inputs = { "hello", "how are you?",
            " this string has wide spaces ", " " };
    int[] outputs = { 1, 3, 5, 0 };
    for (int i = 0; i < outputs.length; i++) {
        System.out.printf("Expected: %d, Actual: %d, %s%n",
                wordCount(inputs[i]), outputs[i],
                wordCount(inputs[i]) == outputs[i] ? "Pass" : "Fail");
    }
}

您的wordCount方法需要考虑null。接下来,您可以使用String.split(String)创建令牌数组。你感兴趣的只是它的长度。像

这样的东西
public static int wordCount(String s) {
    String t = (s == null) ? "" : s.trim();
    return t.isEmpty() ? 0 : t.split("\\s+").length;
}

它通过您提供的测试条件,生成输出

Expected: 1, Actual: 1, Pass
Expected: 3, Actual: 3, Pass
Expected: 5, Actual: 5, Pass
Expected: 1, Actual: 1, Pass