How to get distinct characters?

前端 未结 9 1944
南旧
南旧 2020-12-10 10:21

I have a code like

string code = \"AABBDDCCRRFF\";

In this code, I want to retrieve only distinct characters

The Output should be l

9条回答
  •  粉色の甜心
    2020-12-10 11:05

    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 charDict =new Dictionary();
            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(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
    

提交回复
热议问题