gpt4 book ai didi

java - 使用键值对解析字符串响应并将它们添加到映射或数组中

转载 作者:行者123 更新时间:2023-11-29 08:23:04 25 4
gpt4 key购买 nike

我收到一个响应,其中包含由 分隔的键值对:

USER: 0xbb492894B403BF08e9181e42B07f76814b10FEdc
IP: 10.0.2.6
NETMASK: 255.255.0.0
SUPERNODE: tlcsupernode.ddns.net
PORT: 5000
COMMUNITY: tlcnet
PSK: mysecret
MAC: 00:02:ff:00:02:06

为了解析和存储它们,我使用以下代码:

Map<String, String> map = new HashMap<String, String>();
String[] parts = response.trim().split(":");

for (int i = 0; i < parts.length; i += 2) {
map.put(parts[i], parts[i + 1]);
}

for (String s : map.keySet()) {
System.out.println(s + " is " + map.get(s));
Log.d("Testing", " "+s + " is " + map.get(s));
}

但是由于 MAC 有多个 : 分隔符,我无法正确解析它。

我从以下链接获得了帮助: Split string into key-value pairs

最佳答案

使用 Java 8 流,您可以将其作为一个内衬来完成。

String resp = "USER: 0xbb492894B403BF08e9181e42B07f76814b10FEdc\n" + 
"IP: 10.0.2.6\n" +
"NETMASK: 255.255.0.0\n" +
"SUPERNODE: tlcsupernode.ddns.net\n" +
"PORT: 5000\n" +
"COMMUNITY: tlcnet\n" +
"PSK: mysecret\n" +
"MAC: 00:02:ff:00:02:06";

Map<String, String> map = Arrays.asList(resp.split("\\R")).stream().map(x -> x.split(":", 2)).collect(Collectors.toMap(x -> x[0], x -> x[1].trim()));

for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(String.format("Key: %s, Value: %s", entry.getKey(), entry.getValue()));
}

打印,

Key: SUPERNODE, Value: tlcsupernode.ddns.net
Key: NETMASK, Value: 255.255.0.0
Key: COMMUNITY, Value: tlcnet
Key: PORT, Value: 5000
Key: IP, Value: 10.0.2.6
Key: PSK, Value: mysecret
Key: USER, Value: 0xbb492894B403BF08e9181e42B07f76814b10FEdc
Key: MAC, Value: 00:02:ff:00:02:06

这里,\\R(匹配任何类型的换行符)用换行符拆分你的响应字符串,使用 : 进一步拆分,第二个参数为 2 以拆分字符串获取最多两个值,最后使用 Collectors.toMap

收集为 Map

编辑:

对于旧版本的 Java,您可以使用简单的 for 循环,

String resp = "USER: 0xbb492894B403BF08e9181e42B07f76814b10FEdc\n" + "IP: 10.0.2.6\n" + "NETMASK: 255.255.0.0\n"
+ "SUPERNODE: tlcsupernode.ddns.net\n" + "PORT: 5000\n" + "COMMUNITY: tlcnet\n" + "PSK: mysecret\n"
+ "MAC: 00:02:ff:00:02:06";
Map<String, String> map = new HashMap<>();

for (String line : resp.split("\\R")) {
String[] keyValue = line.split(":", 2);
map.put(keyValue[0], keyValue[1]);
}

for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(String.format("Key: %s, Value: %s", entry.getKey(), entry.getValue()));
}

关于java - 使用键值对解析字符串响应并将它们添加到映射或数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55816360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com