【问题标题】:Java Counting number of words in a string without using split or StringTokenizers etcJava在不使用拆分或StringTokenizers等的情况下计算字符串中的单词数
【发布时间】:2015-04-05 19:21:07
【问题描述】:

程序要求输入字符串,然后输入最小字长。 如果单词小于最小字长,则不计算在内。 我试图在不使用 split() 或其他所有帖子所说的解决这些问题的情况下执行该程序。

我想也许我必须检查第一个单词,最后一个单词,然后是中间的单词。但我遇到了麻烦。我在这上面花了太长时间,我想不通。

IO 是用于输入、输出等的不同类。

public class WordCount {

public static void main(String[] args) {
    int minLength;

    System.out.println("Enter a string.");
    String string=IO.readString();
    String str1=string.toLowerCase(); //changes all characters in the string to lower case
    String str=str1.trim(); //Trims all spaces in the end.

    System.out.println("Enter minimum length for each word.");
    minLength=IO.readInt();

    int num=wordCount(str, minLength);
    IO.outputIntAnswer(num);

}

public static int wordCount(String str, int minLength){     //Method that counts words. 
    int count=0;

    // First Word
    for(int i=0;i<str.length();i++){
        if (str.charAt(i)==' '){
            String firstWord=str.substring(0,i);
            if (firstWord.length()>=minLength){
                count++;
            }
        }
    }

    // Last Word
    for (int i=str.length()-1;i>0;i--){
        if(str.charAt(i)==' '){
            String lastWord=str.substring(i, str.length()-1);
            if(lastWord.length()>=minLength){
                count++;
            }
            for (int j=0; j<i;j++){  //An attempt to find other words in between..does not work
                if(str.charAt(j)==' '){
                    String word=str.substring(j+1, str.indexOf(' ', j+1));
                    if(word.length()>=minLength){
                        count++; 
                    }
                }
            }
        }
    }
    return count;
   }
}

【问题讨论】:

  • ===+-*&gt;&lt;/ 和逗号之后的两边各留一个空格在{ 之前和;'之后。当代码像这样被挤在一起时,看起来很俗气且难以阅读。难以维护。我在一个内核小组工作,在那里你不仅不允许将代码放入格式错误的存储库中,而且即使尝试也会遇到麻烦。查找 C 美化器和格式化程序。你不会找到一个单一的标准来说明你所做的事情在更广泛的社区中是可以接受的。如果您想要一份工作,请学习格式化它。
  • Checkout AStyle 其实你想要一个面向 Java 的等价物,但格式基本相同
  • 让我们从您不想使用split() 或听取之前答案中给出的任何建议开始。
  • 您还可以使用 Java 的 java.util.regex.* 类,例如 PatternMatcher 来执行此操作,而且效率更高。这些是值得花时间掌握的,因为从长远来看,它们会为你节省大量时间。

标签: java


【解决方案1】:

这就够了:

public static int wordCount(String str, int min) {
    int count = 0;
    str = str.trim()+" ";
    for(int i=0, st=0; i<str.length(); i++) {
        if(str.charAt(i) != ' ') continue;
        if(i-st >= min) count++;
        st = i+1;
    }
    return count;
}  

【讨论】:

  • 尽管缺少 return 语句,但此代码并未按应有的方式运行。
  • @Neumann,感谢您指出我的愚蠢错误。编辑答案。
  • 如果我做一个单词,不管min,输出都是1
【解决方案2】:

除了您的代码有点杂乱和不足之外,这里的主要问题是您的第一个 FOR 循环在找到第一个单词后并没有停止。实际上,in 对输入字符串中的每个单词进行计数,减去 1。

第二个循环也有同样的问题。

如果你真的想这样做,你应该使用 BREAK 关键字,在必要时停止循环。

编辑

这应该可以工作

public static int wordCount(String str, int minLength) {     //Method that counts words.
    int count = 0;

    for (int i = 0, wordLength = 0; i < str.length() + 1; i++) {
        if (i == str.length() || str.charAt(i) == ' ') {
            if (wordLength >= minLength) {
                count++;
            }
            wordLength = 0;
        } else {
            wordLength++;
        }
    }

    return count;
}

【讨论】:

  • 感谢这个工作,但我怎样才能让它不会把标点符号或数字算作单词呢?
  • 那么你应该在for循环的第一个if语句中使用正则表达式。
【解决方案3】:

请试试这个。 这会处理额外的空格、前导空格和尾随空格。

public class WordsCount {
   static String str = " I Love Java  for  its  oops  concepts  ";
   static int i;
   static int count = 0;

   public static int numOfWords(String str) {
   int length = str.length();
   for(i=0;i<length;) {
      if(str.charAt(i)!=' ') {
          while(str.charAt(i)!=' ') {
             i++;
             if(i>=str.length())
                break;
          }
          count = count+1;
      } else {
          i++;
      }
  }
  return count;
  }

  public static void main(String[] args) {
      count = numOfWords(str);
      System.out.println("Count of words is : "+count);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2019-12-08
    • 2014-04-23
    • 2019-10-04
    • 2021-01-05
    相关资源
    最近更新 更多