[英]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.