【问题标题】:Counting sentences, only sentences ending with punctuation + 2 spaces计算句子,只有以标点符号结尾的句子 + 2 个空格
【发布时间】:2014-06-17 13:15:10
【问题描述】:

我正在尝试弄清楚如何制作一个句子计数器,我有,但问题是,只有当句号/问号/等后面有两个空格时,我才需要它来计算一个句子。

例如,使用我的代码,如果您输入字符串“你好,我的名字是 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;
  }

【问题讨论】:

  • 其实我是用正则表达式搞定的,真的很简单。
  • 已发布,必须等待 8 小时才能回答我自己的问题

标签: java string count words sentence


【解决方案1】:

其实我知道了,使用正则表达式也超级简单。

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 语句假设用户输入了至少一个句子,并在计数中添加了一个假设他们不会在最后一句话的末尾放置两个空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2021-04-06
    • 2020-02-16
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多