gpt4 book ai didi

javascript - 如何获取像这样的字符串删除Java中的重复字符串

转载 作者:行者123 更新时间:2023-12-03 06:51:04 24 4
gpt4 key购买 nike

我将数组从 jquery 发送到 Controller ,并且该数组在 Controller 中作为字符串获取 String getIdVal = ParamUtil.getString(resourceRequest, "getId");
String getIds 中的值类似于 getIdVal ="1_ABC,2_ABC,3_ABC,4_NMO,5_NMO,6_XYZ";

我正在尝试获得结果,但没有成功。
(考虑到 1 是键 ABC 是值)
我想从所有键中删除 ABC(即重复值)并在末尾仅附加一次。同时我希望重复值的键应该像这样 (1-2-3_ABC)
最后字符串应该像这样 "1-2- 3_ABC,4-5_NMO,6_XYZ”

这里我尝试根据逗号进行分割,但我不知道如何解决。

 List<String> keysVals = new ArrayList<String>(Arrays.asList(getIdVal .split(",")));
String getKeyVal;
String[] getKeys;
String key;
String value;
for (String getKeysVals : keysVals) {
getKeyVal = getKeysVals;
getKeys = getKeyVal.split("\\_");
key = getKeys[0];
value = getKeyVal.substring(getKeyVal.lastIndexOf("_") + 1) .trim();
// i am not getting how to check for dublicate
}

最佳答案

你的意思是这样的吗?

private static String mergeKeys(String input) {
Map<String, StringBuilder> valKeys = new TreeMap<>();
if (! input.isEmpty())
for (String keyVal : input.split(",")) {
int idx = keyVal.indexOf('_');
String key = keyVal.substring(0, idx);
String val = keyVal.substring(idx + 1);
StringBuilder builder = valKeys.get(val);
if (builder == null)
valKeys.put(val, new StringBuilder(key));
else
builder.append('-').append(key);
}
StringJoiner result = new StringJoiner(",");
for (Entry<String, StringBuilder> entry : valKeys.entrySet())
result.add(entry.getValue().append('_').append(entry.getKey()).toString());
return result.toString();
}

或者相同逻辑的缓慢版本,使用string = string + string(哎呀!):

private static String mergeKeys(String input) {
Map<String, String> valKeys = new LinkedHashMap<>();
if (! input.isEmpty())
for (String keyVal : input.split(",")) {
int idx = keyVal.indexOf('_');
String key = keyVal.substring(0, idx);
String val = keyVal.substring(idx + 1);
String prevKeys = valKeys.get(val);
valKeys.put(val, prevKeys == null ? key : prevKeys + "-" + key);
}
String result = "";
for (Entry<String, String> entry : valKeys.entrySet())
result += "," + entry.getValue() + "_" + entry.getKey();
return result.substring(1); // skip leading comma
}

测试

System.out.println(mergeKeys("1_ABC,2_ABC,3_ABC,4_NMO,5_NMO,6_XYZ"));

输出

1-2-3_ABC,4-5_NMO,6_XYZ

关于javascript - 如何获取像这样的字符串删除Java中的重复字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37493804/

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