How to use String object to parse input in Java
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.
精彩评论