java java中如何从字符串中提取子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4710138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to extract a substring from a string in java
提问by JavaMobile
dear all, i have a string like this, "...1name: john, 2name: lice, 3name: mike...". i want to output its substring "1name: john". its position in the string is not fixed. i also use the substring method but can not get it. so could you give me a help.
亲爱的,我有一个这样的字符串,“...1name:john,2name:虱子,3name:mike...”。我想输出它的子字符串“1name:john”。它在字符串中的位置不固定。我也使用 substring 方法,但无法获取。所以你能给我一个帮助吗?
thank you.
谢谢。
回答by Chris Dennett
String s = str.split(",")[n].trim();
I suggest making a map if the position is random:
如果位置是随机的,我建议制作一张地图:
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);
}
The map will thus contain a list of person IDs to their respective value strings. If you wish to store names only as value elements of the map:
因此,该地图将包含人员 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);
}
It'd be easier to use a StringTokenizer in the second example for the key=value pairs if you want to store more data, but I don't know what your delimiter is. You'd also need to store objects as values of the map to store the info.
如果您想存储更多数据,在第二个示例中为 key=value 对使用 StringTokenizer 会更容易,但我不知道您的分隔符是什么。您还需要将对象存储为地图的值以存储信息。
回答by Chris Dennett
String s = "1name: john, 2name: lice, 3name: mike";
String[] names = s.split(", "); // comma and space
for(String name : names){
System.out.println(name);
}