使用String.Join将数组转换为string(C#)后,从string中删除额外的逗号

快速问题在这里。 我使用String.Join将数组转换为string。 我遇到的一个小问题是,在数组中,一些索引位置将是空白的。 下面是一个例子:

array[1] = "Firstcolumn" array[3] = "Thirdcolumn" 

通过使用String.Join(“,”,数组),我会得到以下内容:

Firstcolumn ,, Thirdcolumn

注意额外的,。 如何从string中删除多余的逗号,或者在使用String.Join时最好不要包含空白索引?

尝试这个 :):

 var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s))); 

这将只join不是null""的string。

一个简单的解决scheme是使用linq,在join之前过滤掉空的项目。

 // .net 3.5 string.Join(",", array.Where(item => !string.IsNullOrEmpty(item)).ToArray()); 

在.NET 4.0中,如果还想过滤掉空白或仅包含空格字符的项目,则还可以使用string.IsNullOrWhiteSpace (请注意,在.NET 4.0中,不必在此情况下调用ToArray ):

 // .net 4.0 string.Join(",", array.Where(item => !string.IsNullOrWhiteSpace(item))); 

你可以使用linq删除空的字段。

 var joinedString = String.Join(",", array.Where(c => !string.IsNullOrEmpty(c)); 
 String.Join(",", array.Where(w => !string.IsNullOrEmpty(w)); 

扩展方法:

 public static string ToStringWithoutExtraCommas(this object[] array) { StringBuilder sb = new StringBuilder(); foreach (object o in array) { if ((o is string && !string.IsNullOrEmpty((string)o)) || o != null) sb.Append(o.ToString()).Append(","); } sb.Remove(sb.Length - 1, 1); return sb.ToString(); } 

正则expression式解答:

 yourString = new Regex(@"[,]{2,}").Replace(yourString, @","); 
 string.Join(",", Array.FindAll(array, a => !String.IsNullOrEmpty(a))); 

这个怎么样? 缺点和优点比较LINQ解决scheme? 至less它更短。

 string.Join(",", string.Join(",", array).Split({","}, StringSplitOptions.RemoveEmptyEntries)); 

V( '_')V

简单的扩展方法

 namespace System { public static class Extenders { public static string Join(this string separator, bool removeNullsAndWhiteSpaces, params string[] args) { return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args); } public static string Join(this string separator, bool removeNullsAndWhiteSpaces, IEnumerable<string> args) { return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args); } } } 

用法:

 var str = ".".Join(true, "a", "b", "", "c"); //or var arr = new[] { "a", "b", "", "c" }; str = ".".Join(true, arr);