java里如何判断一句话里单词的个数
"ThankyouforapplyingforajobatExo-web.Itisourpleasuretowelcomeyouforaninitialtestandin...
"Thank you for applying for a job at Exo-web.It is our pleasure to
welcome you for an initial testand interview's as follows" 展开
welcome you for an initial testand interview's as follows" 展开
展开全部
BreakIterator boundary = BreakIterator.getWordInstance();
boundary.setText(s);
int start = boundary.first();
int b = 0;
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()){
String sub = s.substring(start, end);
if(sub.length()>1){
b++;
}else if(sub.length() == 1){
Pattern pattern = Pattern.compile("^[a-zA-Z]$");
Matcher matcher = pattern.matcher(sub);
if ( matcher.matches() ) {
b++;
}
}
}
System.out.println(b);
应该没啥大问题
如果数字也算的话,正则表达式改成^[a-zA-Z0-9]$
。。发现bug,句号不会分割。。
可以考虑先split('.')成为字符串数组在来用这个方法。
String[] array = str.split("\\.");
int b = 0;
for (String s : array) {
BreakIterator boundary = BreakIterator.getWordInstance();
boundary.setText(s);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()){
String sub = s.substring(start, end);
if(sub.length()>1){
b++;
System.out.println(sub);
}else if(sub.length() == 1){
Pattern pattern = Pattern.compile("^[a-zA-Z]$");
Matcher matcher = pattern.matcher(sub);
if ( matcher.matches() ) {
b++;
System.out.println(sub);
}
}
}
}
boundary.setText(s);
int start = boundary.first();
int b = 0;
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()){
String sub = s.substring(start, end);
if(sub.length()>1){
b++;
}else if(sub.length() == 1){
Pattern pattern = Pattern.compile("^[a-zA-Z]$");
Matcher matcher = pattern.matcher(sub);
if ( matcher.matches() ) {
b++;
}
}
}
System.out.println(b);
应该没啥大问题
如果数字也算的话,正则表达式改成^[a-zA-Z0-9]$
。。发现bug,句号不会分割。。
可以考虑先split('.')成为字符串数组在来用这个方法。
String[] array = str.split("\\.");
int b = 0;
for (String s : array) {
BreakIterator boundary = BreakIterator.getWordInstance();
boundary.setText(s);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()){
String sub = s.substring(start, end);
if(sub.length()>1){
b++;
System.out.println(sub);
}else if(sub.length() == 1){
Pattern pattern = Pattern.compile("^[a-zA-Z]$");
Matcher matcher = pattern.matcher(sub);
if ( matcher.matches() ) {
b++;
System.out.println(sub);
}
}
}
}
2013-07-07
展开全部
String.split(' ').length()
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2013-07-07
展开全部
你可以通过判断句子中空格的个数来判断单词的个数。
另外注意一下,标点符号。
另外注意一下,标点符号。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |