在C#中分隔字符串时,按特定字符进行分隔的时候可能会遇到空值,如何我现在传入的是Id的字符串,如:"1501,1502,1503,,1505",以逗号分隔,由于各种原因,导致传入的字符串中有连续的逗号,如果我要利用这一串字符串得到ID数组作为Sql查询的条件,那么我必须对这种情况进行处理。
  实例:

 

//数组转换成字符串,字符串切割成数组.
string[] array = new[] {"1m2", "", "ww", "mm", "acas,"};//集合初始化.
string arrayString = string.Join(",", array);//把数组按指定的分隔符转换成字符串.
int count = arrayString.Count(s => s == 'a');//计算某个字符在字符串中出现的次数.
string[] shuzu = arrayString.Split(',');//把string字符串按指定的字符切割成数组.
//处理各种情况多余的逗号.
string zifu = ",1,2,,3,,,4,5,6,,7,8,,,9,";
string a = Regex.Replace(zifu, ",{2,}", ",");//将连续两个及以上的逗号替换成一个逗号.
string b = Regex.Replace(zifu, "^\,|(\,{2,})|\,$", "");//开头和结尾不能是中英文逗号,不能有连续中英文逗号.
string c = Regex.Replace(zifu, "^\,|\,$", "");//不能以逗号开头或结尾.
string d = Regex.Replace(a, "^\,|\,$", "");//不能以逗号开头或结尾.
string zifu1 = ",1,2,3,";//以逗号开头和结尾.
string e = Regex.Replace(zifu1, "^\,&\,$", "");//不能以逗号开头和结尾,正则无效.
string f = Regex.Replace(zifu1, "^\,|\,$", "");//不能以逗号开头或结尾,满足.
string zifu2 = ",1,2,3";//以逗号开头.
string i = Regex.Replace(zifu2, "^\,&\,$", "");//不能以逗号开头和结尾,正则无效.
string j = Regex.Replace(zifu2, "^\,|\,$", "");//不能以逗号开头或结尾,满足.
string zifu3 = "1,2,3,";//以逗号结尾.
string g = Regex.Replace(zifu3, "^\,&\,$", "");//不能以逗号开头和结尾,正则无效.
string h = Regex.Replace(zifu3, "^\,|\,$", "");//不能以逗号开头或结尾,满足.