C# 寻找第一个不重复的字符
static char FirstUniqueChar(string str) { if (str== null|| str.Length == 0) { throw new Exception("Input can't be empty"); } char[] chrArr = str.ToCharArray(); Hashtable ht = new Hashtable(); for (int i = 0; i < str.Length; i++) { if (ht.Contains(str[i])==false) { ht.Add(str[i], 1); } else { ht[str[i]] = 2; } } for (int i = 0; i < str.Length; i++) { if (ht[str[i]].ToString()=="1") { return str[i]; } } throw new Exception("No unique char."); }
网上查找了下,找到了LINQ的实现,太惊艳了,30行变成3行。
static char FirstUChar(string str) { var filter = str.ToCharArray().GroupBy(s => s).Where(g => g.Count() == 1).Select(g => g.Key); var result = string.Join("", filter.ToArray()); return result[0]; }