【发布时间】:2017-12-17 13:46:05
【问题描述】:
我正在编写代码来查找字符串中的单词数,代码如下:
package exercises;
import java.util.Scanner;
public class count {
public static int countwords(String str){
int count=0;
String space="";
String[] words=str.split(space);
for(String word:words){
if(word.trim().length()>0){
count++;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the string");
Scanner input=new Scanner(System.in);
String s=input.nextLine();
System.out.println(countwords(s));
}
}
为了练习,我再次将这段代码写成
package exercises;
import java.util.Scanner;
public class count {
public static int countwords(String str){
int count=0;
String space="";
String[] words=str.split(space);
for(String word:words){
if(word.trim().length()>0){
count++;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the string");
Scanner input=new Scanner(System.in);
String s=input.nextLine();
System.out.println(countwords(s));
}
}
我只是想知道为什么这些代码的代码输出不同?虽然我逐行检查了代码,但我找不到这两个代码的输出不同的原因?谁能帮忙
【问题讨论】:
-
你在
str.split("")失去了我...你为什么要分割空字符串,而不是空格(或空白)?