gpt4 book ai didi

java - 将字符串存储到包含出现次数的哈希表中

转载 作者:行者123 更新时间:2023-12-02 08:54:21 27 4
gpt4 key购买 nike

我有一个返回某种字符串的方法。我想将单个单词及其出现次数存储在 HashMap 中?

public static void main(String[] args) {
String s = "{link:hagdjh, matrics:[{name:apple, value:1},{name:jeeva, value:2},{name:abc, value:0}]}";

String[] strs = s.split("matrics");
System.out.println("Substrings length:" + strs.length);
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}

}

例如,我有一个字符串 - "{link: https://www.google.co.in/ ,matrics:[{name:apple, value:1},{name:graph, value:2},{name:abc, value:0 }]}";

Now my hashmap should look like

apple = 1
graph = 2
abc = 0

我应该如何进行?

我知道如何使用 HashMap。在这种情况下,我的问题是我不知道如何解析给定的字符串并存储单词及其出现次数。

最佳答案

String regex = "\\{name:(.*), value:(\\d+)\\}";
HashMap<String, Integer> link = new HashMap<>();

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);

while (matcher.find()){
String found = matcher.group(1);
String number = matcher.group(2);
link.put(found, Integer.parseInt(number));
}

关于java - 将字符串存储到包含出现次数的哈希表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60580554/

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