1700442814
1700442815
如果考虑使用一个循环来处理这样的“异常”情况,会使程序的稳定性变差,而且要考虑太多太多的因素,这让程序的复杂性也大大提高了。那如何处理呢?可以考虑使用正则表达式,代码如下:
1700442816
1700442817
public static void main(String[]args){
1700442818
1700442819
//接收键盘输入
1700442820
1700442821
Scanner input=new Scanner(System.in);
1700442822
1700442823
while(input.hasNext()){
1700442824
1700442825
String str=input.nextLine();
1700442826
1700442827
//正则表达式对象
1700442828
1700442829
Pattern pattern=Pattern.compile(”\b\w+\b”);
1700442830
1700442831
//生成匹配器
1700442832
1700442833
Matcher matcher=pattern.matcher(str);
1700442834
1700442835
//记录单词数量
1700442836
1700442837
int wordsCount=0;
1700442838
1700442839
//遍历查找匹配,统计单词数量
1700442840
1700442841
while(matcher.find()){
1700442842
1700442843
wordsCount++;
1700442844
1700442845
}
1700442846
1700442847
System.out.println(str+“单词数:”+wordsCount);
1700442848
1700442849
}
1700442850
1700442851
}
1700442852
1700442853
准不准确,我们来看相同的输入所产生的结果:
1700442854
1700442855
Today is Monday
1700442856
1700442857
Today is Monday单词数:3
1700442858
1700442859
Today is Monday
1700442860
1700442861
Today is Monday单词数:3
1700442862
1700442863
Today is Monday?No!
[
上一页 ]
[ :1.700442814e+09 ]
[
下一页 ]