[英]Convert string to array in Java?
我有一个字符串,其值如下所示(格式相同):
name:xxx
occupation:yyy
phone:zzz
我想将其转换为数组,并使用索引获取占用值。
有什么建议么?
基本上,您将使用Java的split()
函数:
String str = "Name:Glenn Occupation:Code_Monkey";
String[] temp = str.split(" ");
String[] name = temp[0].split(":");
String[] occupation = temp[1].split(":");
结果值为:
name[0] - Name
name[1] - Glenn
occupation[0] - Occupation
occupation[1] - Code_Monkey
阅读有关Split函数的信息。 您可以先用“”分隔文本,然后用“:”分隔文本
我建议使用String的split函数 。
听起来您想转换为属性Map而不是数组。
例如
String text = "name:xxx occupation:yyy phone:zzz";
Map<String, String> properties = new LinkedHashMap<String, String>();
for(String keyValue: text.trim().split(" +")) {
String[] parts = keyValue.split(":", 2);
properties.put(parts[0], parts[1]);
}
String name = properties.get("name"); // equals xxx
这种方法使您的值可以按任何顺序排列。 如果缺少键,则get()将返回null。
如果您仅对职业价值感兴趣,则可以执行以下操作:
String s = "name:xxx occupation:yyy phone:zzz";
Pattern pattern = Pattern.compile(".*occupation:(\\S+).*");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
String occupation = matcher.group(1);
}
str = "name:xxx occupation:yyy phone:zzz
name:xx1 occupation:yy3 phone:zz3
name:xx2 occupation:yy1 phone:zz2"
name[0] = str.subtsring(str.indexAt("name:")+"name:".length,str.length-str.indexAt("occupation:"))
occupation[0] = str.subtsring(str.indexAt("occupation:"),str.length-str.indexAt("phone:"))
phone[0] = str.subtsring(str.indexAt("phone:"),str.length-str.indexAt("occupation:"))
我得到了解决方案:
String[] temp= objValue.split("\n");
String[] temp1 = temp[1].split(":");
String Value = temp1[1].toString();
System.out.println(value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.