3 回答

TA貢獻1810條經驗 獲得超5個贊
您可以使用BreakIterator,并檢測不同類型的文本邊界
在你的情況下句子:
private static void markBoundaries(String target, BreakIterator iterator) {
StringBuffer markers = new StringBuffer();
markers.setLength(target.length() + 1);
for (int k = 0; k < markers.length(); k++) {
markers.setCharAt(k, ' ');
}
int count = 0;
iterator.setText(target);
int boundary = iterator.first();
while (boundary != BreakIterator.DONE) {
markers.setCharAt(boundary, '^');
++count;
boundary = iterator.next();
}
System.out.println(target);
System.out.println(markers);
System.out.println("Number of Boundaries: " + count);
System.out.println("Number of Sentences: " + (count-1));
}
public static void main(String[] args) {
Locale currentLocale = new Locale("en", "US");
BreakIterator sentenceIterator
= BreakIterator.getSentenceInstance(currentLocale);
String someText = "He name is Walton D.C. and he just completed his B.Tech last year.";
markBoundaries(someText, sentenceIterator);
someText = "This order was placed for QT3000! MK?";
markBoundaries(someText, sentenceIterator);
}
輸出將是:
He name is Walton D.C. and he just completed his B.Tech last year.
^ ^
Number of Boundaries: 2
Number of Sentences: 1
This order was placed for QT3000! MK?
^ ^ ^
Number of Boundaries: 3
Number of Sentences: 2

TA貢獻1797條經驗 獲得超4個贊
解決方案可能是在點的情況下,您可以檢查后面是否有空格和大寫字母。
“[點][空格][大寫字母]”
這將是對判決的肯定
更新相同的代碼:
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! MK? \n Thats amazing. \n But I am not sure.";
String pattern = "([.!?])([\\s\\n])([A-Z]*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
int count=0;
while (m.find( )) {
count++;
}
count++; //for the last line, which will not get included here.
System.out.println("COUNT=="+count);
}

TA貢獻1798條經驗 獲得超7個贊
簡單的方法
公共類計數線{
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="Find the number Sentence";
int count=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)==' ') {
count++;
}
}
count=count+1;
System.out.println(count);
}
}
- 3 回答
- 0 關注
- 182 瀏覽
添加回答
舉報