筛选C#中逗号分隔的字符串

本文关键字:分隔 字符串 筛选 | 更新日期: 2023-09-27 18:11:44

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

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

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

"Apple,Banana,Mango,Strawberry". 

我尝试了以下代码,它很有效。

在C#(.NET2.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;
}

筛选C#中逗号分隔的字符串

您也可以使用Regex:

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

我认为以下内容应该能在任何.NET版本上发挥作用:

string[] TrimAll( string[] input )
{
    var result = new List<string>();
    foreach( var s in input )
        result.Add( s.Trim() );
    }
    return result.ToArray();
}
var delimiters = new [] { ",", "'t", Environment.NewLine };
string result = string.Join(",", TrimAll( input.Split( delimiters, StringSplitOptions.RemoveEmptyEntries ) ) );

编辑:更新以处理空白、制表符和换行符。

假设您的物品不包含空格:

private String CommaSeparatedString(String strWithComma)
{
    string[] tokens = strWithComma
        .Replace(" ", "")
        .Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
    return string.Join(",", tokens);
}

现在我不确定C#2.0是否接受new char[] {','}语法。如果没有,您可以在其他地方定义数组(例如,作为类私有成员(。

这里有一行代码:

var outputString = string.Join(",", inputString.Replace(" ", string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
Regex regex = new Regex(@"'w(?:(?!,| ).)*");
            var items = regex.Matches("Apple ,Banana, , , , Mango ,Strawberry , ").Cast<Match>().Select(m => m.Value);

.NET 2.0版本

List<string> newList = new List<string>();
            Regex regex = new Regex(@"'w(?:(?!,| ).)*");
            string str = "Apple ,Banana, , , , Mango ,Strawberry , ";
            MatchCollection matches = regex.Matches(str);
            foreach (Match match in matches)
            {
                newList.Add(match.Value);
            }
var result = Regex.Replace(strWithComma, ",+", ",").TimEnd(',');
result = Regex.Replace(result, "'s+", string.Empty);

没有正则表达式,没有拆分和连接、修剪等,O(n(时间。StringBuilder是一个非常适合处理字符串的类。

编辑如果字符串没有以字母结尾,它将添加一个逗号。因此添加了一个额外的TrimEnd(','(

string strWithComma = ",Apple   ,Banana, , , ,  Mango  ,Strawberry  , 'n John,";
var sb = new StringBuilder();
var addComma = false;
foreach (var c in strWithComma )
{         
  if (Char.IsLetter(c)) // you might want to allow the dash also: example Anne-Marie
  {
    addComma = true;
    sb.Append(c);         
  }
  else
  {         
    if (addComma)
    {
      addComma = false;
      sb.Append(','); 
    }
  }  
}
string rtn = sb.ToString().TrimEnd(',');

警告此方法仅适用于C#3.0或更高版本。抱歉,伙计们没有把问题读得足够好

这会起作用,但可以做得更容易,比如:

string input = "apple,banana,, 'n,test'n, ,juice";
var parts = from part in input.Split(',')
            let trimmedPart = part.Replace("'n", "")
            where !string.IsNullOrWhiteSpace(trimmedPart)
            select trimmedPart;
string result = string.Join(",", parts);