字符串去重

问:字符串如何去除重复的字符?

  • HashSet 无序不重复,最佳选择

        public static string RemoveRepeatChar(string str)
        {
            HashSet set = new HashSet();
            char[] chars = str.ToCharArray();

            for (int i = 0; i < chars.Length; i++)
            {
                set.Add(chars[i]);
            }

            StringBuilder sb = new StringBuilder();
            foreach (var s in set)
            {
                sb.Append(s);
            }

            return sb.ToString();

        }
  • Linq自带去重的方法
        public static string FilteRepeatChar(string str)
        {
            char[] char_arr = str.ToArray().Distinct().ToArray();
            return string.Join("", char_arr);
        }
  • 用List的Contains方法遍历去重
        public static string NotRepeat(string str)
        {
            ArrayList alist = new ArrayList();
            char[] c_arr = str.ToArray();
            for (int i = 0; i < c_arr.Length; i++)
            {
                if (!alist.Contains(c_arr[i]))
                    alist.Add(c_arr[i]);
            }
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < alist.Count; j++)
            {
                sb.Append(alist[j]);
            }

            return sb.ToString();
        }

 

你可能感兴趣的:(.NET(C#))