编写一个名为wordCount的方法,该方法接受String作为其参数,并返回String中的字数。单词是一个或多个非空格字符的序列(除''之外的任何字符)。例如,调用wordCount(“hello”)应返回1,调用wordCount(“你好吗?”)应返回3,调用wordCount(“此字符串有宽空格”)应返回5,调用wordCount (“”)应返回0.
我做了一个功能:
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个单词:( 是否有预定义的字数统计功能?或者可以更正此代码吗?
答案 0 :(得分:32)
如果您想忽略前导,尾随和重复空格,可以使用
String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
答案 1 :(得分:6)
public static int wordCount(String s){
if (s == null)
return 0;
return s.trim().split("\\s+").length;
}
享受这项功能。
答案 2 :(得分:2)
String str="I am a good boy";
String[] words=str.split("\\s+");
System.out.println(words.length);
答案 3 :(得分:0)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
将此字符串拆分为给定正则表达式的匹配项。
答案 4 :(得分:0)
应该很容易:
String[] arr = "how are you sir".split("\\s");
System.out.printf("Count [%d]%n", arr.length);
答案 5 :(得分:0)
只需使用s.split(" ").length
并使用宽广空格...使用s.trim().replaceAll("\\s+"," ").split(" ").length
答案 6 :(得分:0)
在代码中添加了一些代码:
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;
}
答案 7 :(得分:0)
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;
}
如果不使用预定义功能,这就是您所需要的。我自己测试了一下。如果有任何错误,请告诉我!
答案 8 :(得分:0)
我的几个解决方案:
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;
}