2015-10-17 62 views
0

编写一个名为wordCount的方法,该方法接受String作为其参数并返回String中的单词数。一个单词是一个或多个非空格字符(除''之外的任何字符)的序列。例如,调用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; 
    } 
+0

甲'char'不能相比于空'String',作为误差表示。你打算检查角色是否是空间? 's.charAt(0)!'''' – Andreas

+0

http://stackoverflow.com/questions/8102754/java-word-count-program谷歌首先命中:“java字数” – kongebra

+0

@Andreas \t 是我想它会查看是否存在空格并跳过它,以便只计算单词并且不在计数中包含空格。每当我将“”更改为“'我收到更多的错误通知...... – TeSa

回答

0
public static int wordCount(String s) { 
    if(s!=null) 
     return s.trim().split(" ").length ; 
    return 0; 
} 
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 
相关问题