从Java中的String中删除重复项 [英] Removing duplicates from a String in Java

查看:150
本文介绍了从Java中的String中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历字符串以删除重复的字符。

I am trying to iterate through a string in order to remove the duplicates characters.

例如字符串 aabbccdef 应该变成 abcdef
并且字符串 abcdabcd 应该变成 abcd

For example the String aabbccdef should become abcdef and the String abcdabcd should become abcd

这是我到目前为止所拥有的:

Here is what I have so far:

public class test {

    public static void main(String[] args) {

        String input = new String("abbc");
        String output = new String();

        for (int i = 0; i < input.length(); i++) {
            for (int j = 0; j < output.length(); j++) {
                if (input.charAt(i) != output.charAt(j)) {
                    output = output + input.charAt(i);
                }
            }
        }

        System.out.println(output);

    }

}

什么是最好的方法吗?

推荐答案

将字符串转换为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());

这篇关于从Java中的String中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆