简体   繁体   中英

How to count words in a string method?

Im trying to create a project with a scanner to read a text file, separate by the number of lines, and also count the number of words in each line. Here is my code so far:

    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();
        }


  }

Assuming a word is a group of characters delimited by spaces, then inputString.split(" ") will produce an array of 'words', which you can then count. You might want to do some extra checking to make sure multiple space characters in a row which produce empty words dont get counted - or use a proper regular expression in the .split() method.

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

Everytime you read a new line of the text file, pass it to a method that is going to count the words in that line..

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

You may want to take a look at a post already answered asking to do the same thing.. Count words in a string method?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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