If the format of your input data is consistent then you can simply use a pattern like :
and do the following:
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();
}
Note that here I have used substring()
function to get rid of <
and >
in the starting and ending of the input string before splitting it using the given pattern.
Input:
<manchester united : chelsea : 3 : 2>
<foobar : foo : 5 : 3>
stop
Output:
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 |