c# - 在 C# 中过滤逗号分隔的字符串

标签 c# .net arrays string c#-2.0

我有一个动态字符串值,它可能包含这样的值

"Apple   ,Banana, , , ,  Mango  ,Strawberry  , " 

我想像这样过滤这个字符串

"Apple,Banana,Mango,Strawberry". 

我已经尝试使用以下代码并且它有效。

有没有更好的方法可以在 C#(.NET 2.0)中实现相同的目的?

/// <summary>
/// Convert "Comma Separated String" to "Comma Separated String"
/// </summary>
/// <param name="strWithComma">String having values separated by comma</param>
/// <returns>String separated with comma</returns>
private String CommaSeparatedString(String strWithComma)
{
    String rtn = String.Empty;

    List<String> newList= new List<string>();

    if (String.IsNullOrEmpty(strWithComma))
    {
        return rtn;
    }

    String[] strArray = strWithComma.Split(",".ToCharArray());


    if (strArray == null || strArray.Length == 0)
    {
        return rtn;
    }

    String tmpStr = String.Empty;
    String separator=String.Empty;
    foreach (String s in strArray)
    {
        if (!String.IsNullOrEmpty(s))
        {
            tmpStr =s.Replace(Environment.NewLine, String.Empty);
            tmpStr = tmpStr.Trim();
            if (!String.IsNullOrEmpty(tmpStr))
            {
                newList.Add(tmpStr);
            }
        }
    }

    if (newList != null && newList.Count > 0)
    {

        rtn = String.Join(",", newList.ToArray());
    }
    return rtn;

}

最佳答案

你也可以使用正则表达式:

string str = @"Apple   ,,Banana, , , ,  Mango  ,Strawberry  , ";
string result = Regex.Replace(str, @"(\s*,\s*)+", ",").TrimEnd(',');

关于c# - 在 C# 中过滤逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7817784/

相关文章:

c# - winform应用程序中按钮不可见

.net - 检查 log4net XmlConfigurator 是否成功

c# - 我习惯于让 IDE 在 vb.net 下为我创建事件签名,如何使用 C# 来创建事件签名?

arrays - 获取相对于值 Matlab 排序的数组

c# - 为特定精度截断数字的最有效方法是什么?

c# - mongodb : How do I create text index with C# driver?

c# - 固定大小数组

javascript - 需要通过坐标识别Img标签

c# - 我如何使用 XNA 在 C# 中显示数字和文本?

c# - Windows Phone 使用 NSpeex 编码和解码音频。解码有问题?