How to get distinct characters?

Linq's Distinct returns distinct elements from a sequence. As the String class implements IEnumerable<char>, Distinct in this context returns an IEnumerable<char> containing all of the unique characters in the string.

code.Distinct();

Alternative option using dotNet 2.0 compatible code:

public string RemoveDuplicateChars(string input)
{
    var stringBuilder = new StringBuilder(input);

    foreach (char c in input)
    {
        stringBuilder.Replace(c.ToString(), string.Empty)
                     .Append(c.ToString());
    }

    return stringBuilder.ToString();
}

string code = "AABBDDCCRRFF";
string answer = new String(code.Distinct().ToArray());

Here's an approach that provides the string and a count of the distinct characters...

using System;
using System.Collections.Generic;

namespace StringDict
{
    class Program
    {
        static IDictionary<char, int> charDict =new Dictionary<char, int>();
        static private string _charStr = "s;ldfjgsl;dkkjfg;lsdkfjg;lsdkfjg;lsdkfjg;lsdkfj";
        private static int _outInt=0;
        static void Main(string[] args)
        {
            foreach (var ch in _charStr)
            {
                if (!charDict.TryGetValue(ch,out _outInt))
                {
                    charDict.Add(new KeyValuePair<char, int>(ch,1));
                }
                else
                {
                    charDict[ch]++;
                }
            }
            Console.Write("Unique Characters: ");
            Console.WriteLine('\n');
            foreach (var kvp in charDict)
            {
                Console.Write(kvp.Key);
            }
            Console.WriteLine('\n');
            foreach (var kvp in charDict)
            {
                Console.WriteLine("Char: "+kvp.Key+" Count: "+kvp.Value);
            }
            Console.ReadLine();
        }
    }
}

Output...

Unique Characters:

s;ldfjgk

Char: s Count: 6
Char: ; Count: 6
Char: l Count: 6
Char: d Count: 6
Char: f Count: 6
Char: j Count: 6
Char: g Count: 5
Char: k Count: 6

Tags:

C#