简体   繁体   English

将字符串子集转换为数组变量的最佳方法是什么?

[英]What is the best way to convert a subset of string to array variables?

I have a string like this; 我有这样的字符串;

abc 1/2/3 3/4/5 4/5/6 6/7/7 efg 1 2 3 4 ...

I want to make it into; 我想成为它;

String[] abc = {1/2/3, 3/4/5, 4/5/6, 6/7/7}
int[] efg = {1, 2, 3, 4}

where abc, efg are variables NOT hardcoded but obtained from the string. 其中abc,efg是未硬编码但从字符串中获取的变量。 My sample code doesn't work, so I am not posting it here. 我的示例代码不起作用,因此不在此处发布。 Please let me know what is the most efficient way to achieve this. 请让我知道实现这一目标的最有效方法是什么。 Thanks! 谢谢!

Here is working script which gets very close to your stated requirements. 这是工作脚本,它非常接近您陈述的要求。 It generates a map of key names, where the values of arrays of strings. 它生成键名映射,其中包含字符串数组的值。 I do not map an effort to map to different types of arrays, which just adds complexity, and maybe is even out of scope for what you intend to do with this code. 我不会花很多精力去映射到不同类型的数组,这只会增加复杂性,甚至可能超出您打算使用此代码进行处理的范围。

Map<String, String[]> map = new HashMap<>();
String input = "abc 1/2/3 3/4/5 4/5/6 6/7/7 efg 1 2 3 4";
String[] exps = input.split("\\s+(?=[A-Za-z]+)");
for (String exp : exps) {
    String[] parts = exp.split("\\s+");
    map.put(parts[0], Arrays.copyOfRange(parts, 1, parts.length));
}

// iterate each name, and then print out each string in a given array
for (Map.Entry<String, String[]> entry : map.entrySet()) {
    for (String val : entry.getValue()) {
        System.out.println(entry.getKey() + ": " + val);
    }
}

abc: 1/2/3
abc: 3/4/5
abc: 4/5/6
abc: 6/7/7
efg: 1
efg: 2
efg: 3
efg: 4

If you wanted to make the map more generic, you might have to map string names to Object . 如果要使映射更通用,则可能必须将字符串名称映射到Object But, this doesn't feel clean to me, and I would rather just map every name to an array of the same type. 但是,这对我来说并不干净,我宁愿将每个名称映射到相同类型的数组。

To access, for example, the second value for name efg , you would use: 例如,要访问名称efg的第二个值,可以使用:

map.get("efg")[1]

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

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