Java Scanner - next String until a | is found

微笑、不失礼 提交于 2021-01-27 19:20:50

问题


Currently I'm trying to read through some basic cells, in this format:

+-------+-------+
|       |       |
+-------+-------+

Now I need to get the string representation of the cell's contents and send it off to another method. The problem is that the cells have no pre-defined length. I'm reading these from a file, so my easiest option should be to just use the Scanner I already have set up. Problem is, I don't really know how for this case.

I have a strong feeling that I need to use the pattern somehow, but I'm at a complete loss on how to do it.

I could also probably just build it up somehow, but that strikes me as being painfully slow.


回答1:


See javadoc for Scanner, it has an example :

String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

prints the following output:

 1
 2
 red
 blue 

Well you can use | as delimiter.

EDIT : To use | as a delimiter you should escape it, Use \\s*\\|\\s* or \\s*[|]\\s*. If you use | as it is, then you will get only 1st value 1 and exception InputMismatchException.

See below program and output :

public class Test {
    public static void main(String[] args) {
        String input = "1 | 2 | red | blue |";
        Scanner s = new Scanner(input).useDelimiter("\\s*\\|\\s*"); // or use "\\s*[|]\\s*"
        System.out.println(s.nextInt());
        System.out.println(s.nextInt());
        System.out.println(s.next());
        System.out.println(s.next());
        s.close();
    }
}

Output :

1
2
red
blue


来源:https://stackoverflow.com/questions/12985365/java-scanner-next-string-until-a-is-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!