简体   繁体   中英

Remove duplicates from a string

Say I have a string like this:

anxxnbddc

I want to process this and return a string which contains only the characters which appear in the input string exactly once. Therefore my expected output would be:

abc

I have tried this code:

static string RemoveDuplicates(string key)
{
    string result = "";


    for (int i = 0; i < key.Length - 1; i++)
    {
        if (key[i] != key[i + 1])
        {

            result += key[i];
        }
    }

    return result;
}

but my output is:

anxnbd

How do I get my desired output?

string noDuplicates = new string(input.ToCharArray().Where(c => input.ToCharArray().FindAll(x => x == c).Length == 1).ToArray());

Do this with Linq approach:

string withoutDuplicates= new string(yourString.ToCharArray().Distinct().ToArray());

Must help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM