How to get distinct characters in c#
我有个密码
1 | String code="AABBDDCCRRFF"; |
在这段代码中,我只想检索不同的字符
输出应类似于:
1 | ANS: ABDCRF |
1 2 |
Linq的distinct从序列返回不同的元素。当
1 | code.Distinct(); |
使用Dotnet2.0兼容代码的可选选项:
1 2 3 4 5 6 7 8 9 10 11 12 | 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(); } |
这是一种提供字符串和不同字符计数的方法…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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(' '); foreach (var kvp in charDict) { Console.Write(kvp.Key); } Console.WriteLine(' '); foreach (var kvp in charDict) { Console.WriteLine("Char:"+kvp.Key+" Count:"+kvp.Value); } Console.ReadLine(); } } } |
输出…
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
你可以这样做
1 2 3 4 | var s ="AABBDDCCRRFF"; var result = s.Distinct(); var distinct = result.Aggregate(string.Empty, (current, c) => current + c.ToString()); Console.WriteLine(distinct); |
在林肯怎么样?
1 2 3 | var str ="AABBCCDDDDDDEEEEEFFF"; var unique = str.ToCharArray().Distinct(); Console.WriteLine("Answer: {0}.", string.Join(string.Empty, unique)); |
就为了它-使用一个
1 2 3 4 | string code ="AABBDDCCRRFF"; StringBuilder sb = new StringBuilder(); code.Distinct().ToList().ForEach(c => sb.Append(c)); MessageBox.Show(sb.ToString()); |