【问题标题】:Word count algorithm issue字数算法问题
【发布时间】:2014-05-06 21:02:09
【问题描述】:

所以我正在尝试制作一个字数统计程序,用户可以在其中粘贴文本以获取文本类型的字数以获取字数。大部分情况下,输入文本都有效,但有时当我尝试返回并替换文本时,会出现字符串索引超出范围错误。粘贴有效,但我也遇到了字符串索引超出范围的问题。我的逻辑是这样的:一个空格等于一个单词,两个空格背靠背减去一个单词,字符串的结尾算一个单词。我对 Java 比较陌生,我认为这将是一件容易的事情,我错了!一些帮助/解释将不胜感激!

 public static int getWordCount(String getInput, int e){
    int numberOfWords = 0;
    char l1 = 0;
    char l2 = 0;
    StringBuilder convertInput = new StringBuilder(getInput);
    System.out.println(convertInput);
    for (int i = 0, i1 = 1; i < getInput.length();i++, i1++){
        l2 = convertInput.charAt(i);
        if (l2 == ' '){
            numberOfWords += 1;
            l1 = convertInput.charAt(i1);
        }
        if (i == getInput.length() - 1){
            numberOfWords += 1;
        }
        if (l2 == ' ' && l1 == ' '){
            numberOfWords -= 1;
        }
    }
    return numberOfWords;
 } // end of getWordCount method 

【问题讨论】:

  • 由于i1从1开始,会到达getInput.length()(当我到达getInput.length()-1时),此时convertInput.charAt(i1)会超出范围.
  • “当我尝试返回并替换文本时” - 从概念上讲,不应该在简单地计算单词时替换文本。这对我来说表明您的算法过于复杂(并且看起来确实如此)。有many examples out there给你一些思路,看看能不能帮你清理代码。
  • StringBuilder 是怎么回事?

标签: java string stringbuilder


【解决方案1】:

您可以通过以下方式轻松快速地做到这一点:

String phrase = "word1 word2 word3 word4";
String delims = " "; //u can declare more delims here like delims = " ,.{[]}\"; 
String[] tokens = phrase.split(delims);

tokens.length = number of words in your string

【讨论】:

  • 您应该排除空词(标记)。每次连续有两个分隔符时都会出现空词(例如回车+换行)。
  • 直到现在我才知道字符串标记。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2023-04-05
  • 1970-01-01
  • 2021-10-23
  • 2011-05-04
  • 2016-06-23
相关资源
最近更新 更多