且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Java中的String中删除重复项

更新时间:2022-02-07 02:05:09

将字符串转换为char数组,并将其存储在 LinkedHashSet 。这将保留您的订购,并删除重复。类似于:

Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:

String string = "aabbccdefatafaz";

char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
    charSet.add(c);
}

StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
    sb.append(character);
}
System.out.println(sb.toString());