How to check the end of line using Scanner?

前端 未结 4 1685
陌清茗
陌清茗 2020-12-30 09:38

I have searched similar questions, but none helped.

Consider a file :

hi how are you?
where were you?

I want to do

4条回答
  •  难免孤独
    2020-12-30 10:04

    You can scan the text line by line and split each line in tokens using String.split() method. This way you know when one line has ended and also have all the tokens on each line:

    Scanner sc = new Scanner(input);
    while (sc.hasNextLine()){
        String line = sc.nextLine();
        if (line.isEmpty())
            continue;
        // do whatever processing at the end of each line
        String[] tokens = line.split("\\s");
        for (String token : tokens) {
            if (token.isEmpty())
                continue;
            // do whatever processing for each token
        }
    }
    

提交回复
热议问题