简体   繁体   English

将字符串转换为Java中的数组?

[英]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: 基本上,您将使用Java的split()函数:

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. 阅读有关Split函数的信息。 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. 听起来您想转换为属性Map而不是数组。

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. 如果缺少键,则get()将返回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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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