繁体   English   中英

计算句子,仅以标点符号+ 2个空格结尾的句子

[英]Counting sentences, only sentences ending with punctuation + 2 spaces

我试图弄清楚如何使一个句子计数器成为现实,但问题是,只有当句号/问号/等后面有两个空格时,我才需要它对一个句子进行计数。

例如,使用我的代码,如果输入字符串“ hello,我的名字叫ryan ...”,它将返回3个句子的计数。 我只需要数一句话就可以了。

这个程序也需要数字。 我用空格-1来计数单词。这就是我的问题所在,我要么弄乱了单词数,要么弄乱了句子数。

这是单词计数的方法:

public static int countWords(String str){
     if(str == null || str.isEmpty())
        return 0;

     int count = 0;
     for(int i = 0; i < str.length(); i++){
        if(str.charAt(i) != ' '){
           count++;
           while(str.charAt(i) != ' ' && i < str.length()-1){
              i++;
           }
        }
     }
     return count;
  }

这是计数句子的方法:

public static int sentenceCount(String str) {
     String SENTENCE_ENDERS = ".?!";

     int sentenceCount=0;
     int lastIndex=0; 
     for(int i=0;i < str.length(); i++){  
        for(int j=0;j < SENTENCE_ENDERS.length(); j++){  
           if(str.charAt(i) == SENTENCE_ENDERS.charAt(j)){
              if(lastIndex != i-1){
                 sentenceCount++;
              }
              lastIndex = i;
           }
        }

     }
     return sentenceCount;
  }

实际上,我使用正则表达式也非常简单。

public static int sentenceCount(String str) {

  String regex = "[?|!|.]+[ ]+[ ]";
  Pattern p = Pattern.compile(regex);
  int count = 0;
  Matcher m = p.matcher(str);       
  while (m.find()) {
     count++;
  }
  if (count == 0){
     return 1;
  }
  else {
     return count + 1;
  }
  }  

效果很好,我添加了if语句(假设用户正在输入至少一个句子),并在计数中添加了一个(假设用户不会在最后一个句子的末尾放置两个空格)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM