答案 0 :(得分:6)
String s = str.split(",")[n].trim();
如果位置是随机的,我建议制作地图:
Map<Integer, String> m = new HashMap<Integer, String>();
for (String s : str.split(",")) {
s = s.trim();
int keyvalstart = -1;
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(i)) {
keyvalstart = i;
break;
}
}
if (keyvalstart == -1) continue;
String s_id = s.substring(0, keyvalstart - 1);
String keyvals = s.substring(keyvalstart);
int id = Integer.parseInt(s_id);
m.put(id, keyvals);
}
因此,地图将包含各自值字符串的人员ID列表。如果您希望仅将名称存储为地图的值元素:
Map<Integer, String> m = new HashMap<Integer, String>();
for (String s : str.split(",")) {
s = s.trim();
int keyvalstart = -1;
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(i)) {
keyvalstart = i;
break;
}
}
if (keyvalstart == -1) continue;
String s_id = s.substring(0, keyvalstart - 1);
int id = Integer.parseInt(s_id);
String keyvals = s.substring(keyvalstart);
int valstart = keyvals.indexOf("name: ") + "name: ".length();
String name = keyvals.substring(valstart);
m.put(id, name);
}
如果要存储更多数据,在第二个示例中使用StringTokenizer更容易,因为我想知道你的分隔符是什么。您还需要将对象存储为地图的值以存储信息。
答案 1 :(得分:6)
String s = "1name: john, 2name: lice, 3name: mike";
String[] names = s.split(", "); // comma and space
for(String name : names){
System.out.println(name);
}