我在Java中创建一个命令行实用程序作为实验,我需要解析用户的一串输入。每次出现'&'时,字符串都需要分成几个部分。使用Java中的String对象执行此操作的最佳方法是什么。
这是我的基本代码:
//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);
}
答案 0 :(得分:5)
我认为最简单的方法是
String[] tokens = textLine.split("&");
答案 1 :(得分:0)
Scanner或StringTokenizer是另一种方法。但是对于像这样的简单分隔符,MByd提到的split()方法将完美地工作。