java对字符串中的单词进行计数
我正在编写代码以查找字符串中的字数,代码如下:java对字符串中的单词进行计数,java,string,count,words,Java,String,Count,Words,我正在编写代码以查找字符串中的字数,代码如下: 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:
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));
}
}
我只是想知道为什么这些代码的输出不同?虽然我逐行检查了代码,但我找不到这两个代码输出不同的原因?有人能帮忙吗
String space="";
这是错误的。这是一个空字符串,将被错误使用
你最好用
String space="\\s+";
或
正则表达式“\\s+”是“一个或多个空格符号”由于拆分字符串是“
”
,因此每个字母都将被提取为一个单词
只需更改字符串空间=”代码>到字符串空间=”代码>或字符串空格=“\\s+”代码>,您就可以开始了
正则表达式工具\\s+
指示在出现一个或多个空格后应拆分字符串。另一个选项可能类似于:
public static void main(String[] args) {
System.out.println("Enter the string");
Scanner input=new Scanner(System.in);
String line=input.nextLine();
System.out.println(Arrays.stream(line.split(" ")).count());
}
你在str.split(“”
)把我弄丢了。。。为什么要拆分为空字符串,而不是空格(或空格)?您的意思是“\\s+”?谢谢。还有什么建议可以改进此代码吗?还要添加什么才能在字符串中找到唯一和重复的单词。@ppkumar Anytime:)
public static void main(String[] args) {
System.out.println("Enter the string");
Scanner input=new Scanner(System.in);
String line=input.nextLine();
System.out.println(Arrays.stream(line.split(" ")).count());
}