【问题标题】:write a method to return number of words in a string? edited编写一个方法来返回字符串中的单词数?已编辑
【发布时间】:2015-10-17 02:03:43
【问题描述】:

编写一个名为 wordCount 的方法,该方法接受一个字符串作为其参数并返回字符串中的单词数。单词是一个或多个非空格字符的序列(' ' 以外的任何字符)。例如,调用 wordCount("hello") 应该返回 1,调用 wordCount("你好吗?") 应该返回 3,调用 wordCount("this string has wide spaces") 应该返回 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;
    }

【问题讨论】:

  • A char 不能与空的 String 进行比较,如错误所示。您是否打算检查字符是否为空格? s.charAt(0) != ' '
  • stackoverflow.com/questions/8102754/java-word-count-program google 第一击:“java word count”
  • @Andreas 是的,我希望它查看是否有空格并跳过它,这样只会计算单词而不包括空格。每当我将 "" 更改为 '' 时,我都会收到更多错误通知...

标签: java


【解决方案1】:
 public static int wordCount(String s) {
     if(s!=null)
       return s.trim().split(" ").length ;
     return 0;
}

【讨论】:

    【解决方案2】:

    我将从定义完成开始。通常,这就是您的功能定义完成的时候。一个这样的例子(来自你的问题)可能看起来像

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 2018-05-14
      相关资源
      最近更新 更多