简体   繁体   中英

Convert string to array in Java?

I have a string which has the values like this (format is the same):

name:xxx
occupation:yyy
phone:zzz

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

Basically you would use Java's split() function:

String str = "Name:Glenn Occupation:Code_Monkey";

String[] temp = str.split(" ");
String[] name = temp[0].split(":");
String[] occupation = temp[1].split(":");

The resultant values would be:

name[0] - Name
name[1] - Glenn

occupation[0] - Occupation
occupation[1] - Code_Monkey

Read about Split functnio. You can split your text by " " and then by ":"

我建议使用String的split函数

Sounds like you want to convert to a property Map rather than an array.

eg

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

This approach allows your values to be in any order. If a key is missing, the get() will return null.

If you are only interested in the occupation value, you could do:

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:"))

I got the solution:

String[] temp= objValue.split("\n");
String[] temp1 = temp[1].split(":");
String Value = temp1[1].toString();
System.out.println(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM