如何计算单词之间空格为空格的字符串中的确切单词数?

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

我做了一个function:

public static int wordCount(String s){ int counter = 0; for(int i=0; i<=s.length()-1; i++) { if(Character.isLetter(s.charAt(i))){ counter++; for(i<=s.length()-1; i++){ if(s.charAt(i)==' '){ counter++; } } } } return counter; } 

但我知道这有一个限制,它也将计算字符串中的所有单词完成后的空格数nad它还将计算2个空格,因为可能是2个单词:(是否有预定义的字数计数?或者这段代码可以纠正吗?

如果要忽略可以使用的前导,尾随和重复空格

 String trimmed = text.trim(); int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length; 
 public static int wordCount(String s){ if (s == null) return 0; return s.trim().split("\\s+").length; } 

玩得开心。

 String str="I am a good boy"; String[] words=str.split("\\s+"); System.out.println(words.length); 

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String

将此字符串拆分为给定正则表达式的匹配项。

应该很容易:

 String[] arr = "how are you sir".split("\\s"); System.out.printf("Count [%d]%n", arr.length); 

在代码中添加了一些行:

 public static int wordCount(String s){ int counter=0; for(int i=0;i<=s.length()-1;i++){ if(Character.isLetter(s.charAt(i))){ counter++; for(;i<=s.length()-1;i++){ if(s.charAt(i)==' '){ counter++; i++; while (s.charAt(i)==' ') i++; } } } } return counter; } 

只需使用s.split(" ").lengths.trim().replaceAll("\\s+"," ").split(" ").length和宽空格…使用s.trim().replaceAll("\\s+"," ").split(" ").length

 public static int wordCount(String s){ int counter=0; for(int i=0;i<=s.length()-1;i++){ if(Character.isLetter(s.charAt(i))){ counter++; for(;i<=s.length()-1;i++){ if(s.charAt(i)==' '){ i++; break; } } } } return counter; } 

如果不使用预定义函数,这就是您所需要的。 我自己测试了一下。 如果有任何错误,请告诉我!

我的几个解决方案

 public static int wordcount1(String word) { if (word == null || word.trim().length() == 0) { return 0; } int counter = 1; for (char c : word.trim().toCharArray()) { if (c == ' ') { counter++; } } return counter; } 

//

 public static int wordcount2(String word) { if (word != null || word.length() > 0) { return word.trim().length() - word.trim().replaceAll("[ ]", "").length() + 1; } else { return 0; } } 

//递归

 public static int wordcount3(String word) { if (word == null || word.length() == 0) { return 0; } if (word.charAt(0) == ' ') { return 1 + wordcount3(word.substring(1)); } return wordcount3(word.substring(1)); } 

//

 public static int wordcount4(String word) { if (word == null || word.length() == 0) { return 0; } String check = word.trim(); int counter = 1; for (int i = 0; i < check.length(); i++) { if (i > 0 && Character.isSpaceChar(check.charAt(i)) && !Character.isSpaceChar(check.charAt(i - 1))) { counter++; } } return counter; }