开发者

Convert string to array in Java?

开发者 https://www.devze.com 2023-01-31 09:38 出处:网络
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 i开发者_运维技巧nto an array and get the occupation value using indexes

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 i开发者_运维技巧nto 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 ":"


I would recommend using String's split function.


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

e.g.

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消