将不带反逗号的csv字符串转换为带反逗号的csv字符串

时间:2018-10-25 11:17:49

标签: c# csv

假设,我有一个字符串如下:

string a = "James,Bond,Tom,,,Cruise,"Tom,Hardy",Angelina";

我想要以下输出:

string b = ""James","Bond","Tom","","","Cruise","Tom,Hardy","Angelina"";

我们非常感谢您的帮助,在此先感谢:)

1 个答案:

答案 0 :(得分:1)

我使用下面的扩展方法拆分简单的CSV(我没有写方法)。如果CSV更复杂,我会使用CSV库(想到了CSVHelper和Tiny CSV Parser)。

public static string[] SplitCSV(this String record)
{
   string[] fields;

   Regex oRegex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
   fields = oRegex.Replace(record, "\b").Split('\b');

   return fields;
}

然后编写您的代码以在必要时添加引号:

var a = "James,Bond,Tom,,,Cruise,\"Tom,Hardy\",Angelina";

string[] tokens = a.SplitCSV();

for (int i=0; i<tokens.Length;i++)
{
    if (!tokens[i].StartsWith("\""))
    {
       tokens[i] = "\"" + tokens[i] + "\"";
    }
}

var b = String.Join(",", tokens);