Casey Flynn
Casey Flynn

Reputation: 14038

How to use String object to parse input in Java

I'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);
    }

Upvotes: 1

Views: 2667

Answers (2)

Tauf
Tauf

Reputation: 21

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.

Upvotes: 0

MByD
MByD

Reputation: 137292

I think the simplest way is

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

Upvotes: 5

Related Questions