繁体   English   中英

如何计算字符串方法中的单词?

[英]How to count words in a string method?

我试图用扫描仪创建一个项目,以读取一个文本文件,该文本文件以行数分隔,还计算每行中的单词数。 到目前为止,这是我的代码:

    public void getWordsPerLine(){

      try {
           File file = new File("report.txt");
            Scanner scanner = new Scanner(file);
            int count = 0;


            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                count++;


                if (count <= 9){
                System.out.println("");
                System.out.println("Line Number: " + count);
                System.out.println(line);
            }


            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


  }

假设一个单词是由空格分隔的一组字符,那么inputString.split(“”)将产生一个'words'数组,您可以对其进行计数。 您可能需要做一些额外的检查,以确保连续产生空字的多个空格字符不被计数-或在.split()方法中使用适当的正则表达式。

您可以使用String类的split()方法在空格上分割行,并获取返回数组中元素的数量(等于行中单词的数量)。

每次阅读文本文件的新行时,请将其传递给将对该行中的单词进行计数的方法。

while (scanner.hasNextLine()) {
String line = scanner.nextLine();
countWords(line);
count++;

您可能想看看已经回答并要求做同样事情的帖子。 在字符串方法中计算单词数?

暂无
暂无

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

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