1

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

2 Answers 2

5

I think the simplest way is

String[] tokens = textLine.split("&");
Sign up to request clarification or add additional context in comments.

1 Comment

ahh nice, I like this. Thanks!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.