Suppose, I've a string as below :
string a = "James,Bond,Tom,,,Cruise,"Tom,Hardy",Angelina";
I want the below output :
string b = ""James","Bond","Tom","","","Cruise","Tom,Hardy","Angelina"";
Any help is deeply appreciated, Thanks in Advance :)
I use the extension method below to split simple CSV's (I didn't write the method). If the CSV is more complex I would use a CSV library (CSVHelper and Tiny CSV Parser come to mind).
public static string[] SplitCSV(this String record)
{
string[] fields;
Regex oRegex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
fields = oRegex.Replace(record, "\b").Split('\b');
return fields;
}
Then write your code to add quotes where necessary:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.