日期:2014-05-18  浏览次数:20488 次

字符串过滤
string str="李四,张三,李四,王五,赵六,张三"
怎么把这个字符串中相同的项过滤掉。只留一个啊,逗号不能去掉
我要下面这样的效果
 str="李四,张三,王五,赵六"


------解决方案--------------------
先用Split按逗号分开,得到一个数组
用LINQ,在拼接起来
------解决方案--------------------
C# code

public static string filterRepeatChar(string _val)
{
 string _str = string.Empty;
 string[] strArray = _val.Split(',');
 for (int i = 0; i < strArray.Length; i++)
 {
  for (int j = i + 1; j < strArray.Length; j++)
  {
   if (strArray[j] == strArray[i])
   {
    strArray[i] = string.Empty;
   }
  }
  if (strArray[i]!=string.Empty)
   _str += strArray[i] + ",";
 }
 if (_str.LastIndexOf(",") > -1)
  _str = _str.Substring(0, _str.Length - 1);
 return _str;
}

------解决方案--------------------
C# code

            string str = "李四,张三,李四,王五,赵六,张三";
            var vs = from s in str.Split(',') group s by s into p select new { p.Key, num = p.Count() };
            string ss = string.Empty;
            foreach (var v in vs)
            {
                if (string.IsNullOrEmpty(ss))
                    ss = v.Key;
                else
                    ss = ss + ","+v.Key;
            }
            MessageBox.Show(ss);

------解决方案--------------------
C# code

  string strwr = "李四,张三,李四,王五,赵六,张三";
            var wq = from p in strwr.Split(',').Distinct()
                     select p;
                   
            string rw = "";
            foreach (var kk in wq)
            {
                rw += kk.ToString()+",";
            }
            rw = rw.TrimEnd(',');

------解决方案--------------------
用个冒泡法就可以解决了,相同的去掉
------解决方案--------------------
string.Join(",", str.Split(',').Distinct())