开发者

How to use String object to parse input in Java

开发者 https://www.devze.com 2023-03-06 11:49 出处:网络
I\'开发者_Python百科m creating a command line utility in Java as an experiment, and I need to parse a string of input from the user. The string needs to be separated into components for every occurren

I'开发者_Python百科m creating a command line utility in Java as an experiment, and I need to parse a string of input from the user. The string needs to be separated into components for every occurrence of '&'. What's the best way to do this using the String object in Java.

Here is my basic code:

    //Process p = null;
    Process p = null;
    Runtime r = Runtime.getRuntime();
    String textLine = "";
    BufferedReader lineOfText = new BufferedReader(new InputStreamReader(System.in));

    while(true) {
        System.out.print("% ");
        try {
            textLine = lineOfText.readLine();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //System.out.println(textLine);
    }


I think the simplest way is

String[] tokens = textLine.split("&");


A Scanner or a StringTokenizer is another way to do this. But for a simple delimiter like this, the split() method mentioned by MByd will work perfectly.

0

精彩评论

暂无评论...
验证码 换一张
取 消