谁能告诉我如何从
String s="Bangalore-Chennai-NewYork-Bangalore-Chennai";
输出应该是这样的
String s="Bangalore-Chennai-NewYork-";
使用 Java..
任何帮助将不胜感激.
这一行就搞定了:
public String deDup(String s) {
return new LinkedHashSet<String>(Arrays.asList(s.split("-"))).toString().replaceAll("(^\[|\]$)", "").replace(", ", "-");
}
public static void main(String[] args) {
System.out.println(deDup("Bangalore-Chennai-NewYork-Bangalore-Chennai"));
}
输出:
Bangalore-Chennai-NewYork
请注意订单被保留:)
重点是:
split("-")
将不同的值作为数组提供给我们Arrays.asList()
把数组变成ListLinkedHashSet
保留唯一性和插入顺序 - 它完成了为我们提供唯一值的所有工作,这些值通过构造函数传递toString()
是 [element1, element2, ...]
replace
命令从 toString()
split("-")
gives us the different values as an arrayArrays.asList()
turns the array into a ListLinkedHashSet
preserves uniqueness and insertion order - it does all the work of giving us the unique values, which are passed via the constructortoString()
of a List is [element1, element2, ...]
replace
commands remove the "punctuation" from the toString()
此解决方案要求值不包含字符序列 ", "
- 对此类简洁代码的合理要求.
This solution requires the values to not contain the character sequence ", "
- a reasonable requirement for such terse code.
当然是1行:
public String deDup(String s) {
return Arrays.stream(s.split("-")).distinct().collect(Collectors.joining("-"));
}
如果您不关心保留顺序(即可以删除 first 出现的重复项):
public String deDup(String s) {
return s.replaceAll("(\b\w+\b)-(?=.*\b\1\b)", "");
}
这篇关于从java中的字符串中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!