日期:2014-05-18 浏览次数:20748 次
var str = "ssyyaillxx"; var filter = str.ToCharArray().GroupBy(s => s).Where(g => g.Count() == 1).Select(g => g.Key); var result = string.Join("", filter.ToArray()); Console.WriteLine(result); Console.Read();
------解决方案--------------------
string test_str = "ssyyaillxx"; test_str=string.Join("",test_str.ToCharArray().GroupBy(a => a).Where(a => a.Count() == 1).Select(a=>a.Key).ToArray());//ai
------解决方案--------------------
string str = @"dgsagsdretdddtetwq"; char[] chars = str.ToList<char>().Distinct().ToArray<char>(); str = new string(chars);
------解决方案--------------------
linq代码实现确实要优雅很多 不过你没接触过我这边写了段比较傻的代码 不知道你能不能看懂 主要就是循环然后查看当前字符和前后字符是否相等
static void Main(string[] args) { var testString = "aaabbbcdefffkffff"; var charArray = testString.ToCharArray(); var length = charArray.Length; StringBuilder sb = new StringBuilder(); List<string> returnValue = new List<string>(); for (int i = 1; i < length; i++) { var current = charArray[i]; if (i < length-1) { if (current == charArray[i + 1] || current == charArray[i - 1]) { if (sb.Length != 0) { returnValue.Add(sb.ToString()); sb.Clear(); } continue; } else { sb.Append(current); } } else { if (current == charArray[i - 1]) { continue;//检测最后一个字符是否有重复 } else { sb.Append(current); } } } if (sb.Length != 0) { returnValue.Add(sb.ToString()); } foreach (var temp in returnValue) { Console.WriteLine(temp); } Console.ReadLine(); }