如何将一行用户输入拆分为单独的字符串并存储,例如,如果输入格式如下(对于结果图表)..
home_name : away_name : home_score : away_score
我如何将输入分成4个不同的部分并单独存储? (系统将提示用户仅以上述格式输入,并且我使用while循环继续询问行结果,直到用户进入停止状态。)
答案 0 :(得分:4)
如果输入数据的格式一致,那么您只需使用:
之类的模式并执行以下操作:
public static void main(String[] args) {
/* Scan Inputs */
Scanner in = new Scanner(System.in);
/* Input String */
String input = null;
/* Create StringBuilder Object */
StringBuilder builder = new StringBuilder();
String[] headers = { "home_name: ", "away_name: ", "home_score: ",
"away_score: " };
while (null != (input = in.nextLine())) {
/* Break if user enters stop */
if ("stop".equalsIgnoreCase(input)) {
break;
}
/* Trim the first and the last character from input string */
input = input.substring(1, input.length() - 1);
/* Split the input string using the required pattern */
String tokens[] = input.split(" : ");
/* Print the tokens array consisting the result */
for (int x = 0; x < tokens.length; x++) {
builder.append(headers[x]).append(tokens[x]).append(" | ");
}
builder.append("\n");
}
/* Print Results & Close Scanner */
System.out.println(builder.toString());
in.close();
}
请注意,在使用给定模式拆分输入字符串之前,我已使用substring()
函数删除输入字符串开头和结尾的<
和>
。
<强>输入:强>
<manchester united : chelsea : 3 : 2>
<foobar : foo : 5 : 3>
stop
<强>输出:强>
home_name: manchester united | away_name: chelsea | home_score: 3 | away_score: 2 |
home_name: foobar | away_name: foo | home_score: 5 | away_score: 3 |
答案 1 :(得分:1)
在某些情况下,输入可能有点“不一致”:未提供空格或新版本产生的更改。如果是这种情况,可以使用正则表达式应用一些保护。
public static void main(String[] args) {
boolean validInput = false;
String input = "<home_name : away_name : home_score : away_score>";
String pattern = "<.*:.*:.*:.*>";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
validInput = m.matches();
if(validInput) {
input = input.substring(1, input.length() - 1);
String tokens[] = input.split("\\s*:\\s*");
for (int x = 0; x < tokens.length; x++) {
System.out.println(tokens[x]);
}
} else {
System.out.println("Input is invalid");
}
}
答案 2 :(得分:0)
如果格式与您所描述的完全一致,那么解析它的一种相当有效的方法是:
public static void main(String[] args) {
String line = "<Raptors : T-Rexes : 5 : 10>";
final int colonPosition1 = line.indexOf(':');
final int colonPosition2 = line.indexOf(':', colonPosition1 + 1);
final int colonPosition3 = line.indexOf(':', colonPosition2 + 1);
final String homeName = line.substring(1, colonPosition1 - 1);
final String awayName = line.substring(colonPosition1 + 2, colonPosition2 - 1);
final int homeScore = Integer.parseInt(line.substring(colonPosition2 + 2, colonPosition3 - 1));
final int awayScore = Integer.parseInt(line.substring(colonPosition3 + 2, line.length() - 1));
System.out.printf("%s: %d vs %s: %d\n", homeName, homeScore, awayName, awayScore);
}