简体   繁体   中英

How do I extract unique characters from a string?

I have a string, "aabbcccddeefddg", and I want to extract the unique characters from it. The result set should be "abcdefg".

Note : I don't want to use the String.Distinct function in C#.

Not sure why you don't want to use Distinct , but here's a solution using a HashSet<char> :

HashSet<char> chars = new HashSet<char>();
string s = "aabbcccddeefddg";
foreach(char c in s)
{
    chars.Add(c);
}

foreach(char c in chars)
{
    Console.WriteLine(c);
}

How about this:

static string extract(string original)
        {
            List<char> characters = new List<char>();
            string unique = string.Empty;

            foreach (char letter in original.ToCharArray())
            {
                if (!characters.Contains(letter))
                {
                    characters.Add(letter);
                }
            }

            foreach (char letter in characters)
            {
                unique += letter;
            }

            return unique;
}

Check out the pseudo code below

initialize array index[256] to 0

for (i=0; i<length_of_string; i++)
{
  index[string[i]]++;
}

for (i=0; i<256; i++)
{
  if (index[i] > 0)
    print ascii of **i** 
}

UPDATE

The below loop will print the characters in the order in which it appeared in the original string.

for (i=0; i<256; i++)
{
  if (index[i] > 0)
  {
    index[i] = 0
    print ascii of **i**
  }
}
string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";

var newstr = String.Join("", s.Distinct());

Or split the string into an array of chars. Then loop through it. Take the remainder (everything after the current letter) of the string (with substring) and use String.Replace on it to remove other references of the same letter. Then concatenate the result back with the first part. Do this for every letter.

Problem also solved.

Does this 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