如何解析这个以逗号分隔的字符串?

时间:2013-01-03 16:12:45

标签: c# regex string

我有以下字符串:

"'2014' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'"

我想将1号和2号位置加在一起并将其保存在位置1,例如:

"'2014381' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'"

4 个答案:

答案 0 :(得分:3)

使用String.SplitString.Join

string text = "'2014' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'";
string[] words = text.Split(new[] { "' , '" }, StringSplitOptions.None);
string result = string.Join("", words.Take(2)) + 
                string.Join("' , '", words);

Demo

答案 1 :(得分:3)

var str = "'2014' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'";
var parts = str.Split(new string[] { " , " }, StringSplitOptions.None);

parts[0] = String.Format("'{0}{1}'", parts[0].Replace("'", ""),
                                     parts[1].Replace("'", ""));
str = String.Join(" , ", parts);

答案 2 :(得分:0)

使用此问题中提到的replaceFirst函数:

How do I replace the *first instance* of a string in .NET?

string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

然后你可以这样做:

string updated = ReplaceFirst(original, "' , '", "");

答案 3 :(得分:0)

var input = "'2014' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'";
var delimeter = " , ";

var splits = input.Split(',').Select (i => i.Trim());
var result = splits.Take(2).Aggregate ((x, y) => x + y).Replace("''", "") 
    + delimeter + splits.Skip(1).Aggregate ((x, y) => x + delimeter + y);

输出:

'2014381' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'