例如,如果输入格式如下(对于结果图表),我如何将一行用户输入拆分为单独的字符串并进行存储。
home_name : away_name : home_score : away_score我该如何将输入分成4个不同的部分并分别存储呢?(用户将被提示仅以上述格式输入,我正在使用while循环继续询问行结果,直到用户输入stop)。
发布于 2017-01-05 06:04:24
如果您的输入数据的格式是一致的,那么您可以简单地使用像:这样的模式并执行以下操作:
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 | 发布于 2017-01-05 06:49:52
在某些情况下,输入可能会有一点“不一致”:没有提供空白或新版本产生的更改。如果是这种情况,则可以使用正则表达式应用一些保护。
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");
}
}发布于 2017-01-05 06:58:41
如果格式与您所描述的格式完全相同,那么解析它的一个相当有效的方法是:
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);
}https://stackoverflow.com/questions/41473861
复制相似问题