繁体   English   中英

不使用split方法计算不在字符串数组中的String中的单词

[英]Count words in a String that is NOT in a string array without using split method

我需要计算字符串中的单词。 对于你们中的许多人来说,这看起来非常简单,但从我在类似问题中读到的人们所说的使用数组但我宁愿不这样做。 由于我的字符串来自输入文件并且程序无法硬连线到特定文件,因此它使我的程序复杂化。

到目前为止我有这个:

while(input.hasNext())
    {
        String sentences = input.nextLine();
       int countWords;
       char c = " ";
       for (countWords = 0; countWords < sentences.length(); countWords++)
       {
            if (input.hasNext(c))
                countWords++;
       }

       System.out.println(sentences);
       System.out.println(countWords);
    }

问题是我在这里得到的结果是计算字符串中的字符数量。 我以为它会把char c算作分隔符。 我也尝试使用String c而不是input.hasNext,但编译器告诉我:

Program04.java:39: incompatible types
found   : java.lang.String[]
required: java.lang.String
       String token = sentences.split(delim);

我已经从程序中删除了.split方法。 如何在不使用带有扫描文件的String数组的情况下划分(是正确的单词?)?

不要将扫描仪( input )用于多个操作。 您正在使用它来读取文件中的行,并尝试使用它来计算这些行中的单词。 使用第二个扫描仪来处理线本身,或使用其他方法。

问题是扫描程序在读取时会消耗其缓冲区。 input.nextLine()返回sentences ,但之后就不再有了。 在其上调用input.hasNext()有关sentences 后面字符的信息。

计算sentences单词的最简单方法是:

int wordCount = sentences.split(" ").length;

使用扫描仪,您可以:

Scanner scanner = new Scanner(sentences);
while(scanner.hasNext())
{
     scanner.next();
     wordCount++;
}

或者使用for循环以获得最佳性能(如BlackPanther所述)。

我给你的另一个提示是如何更好地命名你的变量。 countWords应该是wordCount “计数单词”是一个命令,一个动词,而一个变量应该是一个名词。 sentences应该简单地line ,除非你知道两者的线由句子,而这其实是有关您的代码的其余部分。

也许,这就是你要找的东西。

 while(input.hasNext())
{
   String sentences = input.nextLine();
   System.out.println ("count : " + line.split (" ").length);


}

你想要达到的目标还不是很清楚。 但如果您要计算文本文件中的单词数,请尝试此操作

int countWords = 0;

while(input.hasNext())
{
   String sentences = input.nextLine();
   for(int i = 0; i< sentences.length()-1;i++ ) {
       if(sentences.charAt(i) ==  " ") {
          countWords++;
       }
   }
}
System.out.println(countWords);

暂无
暂无

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

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