正在分析C#中的CSV字符串(而不是文件)
本文关键字:文件 字符串 CSV 中的 | 更新日期: 2023-09-27 18:26:14
使用C#,我需要解析一个不是来自文件的CSV字符串。我发现了很多关于解析CSV文件的材料,但实际上没有关于字符串的材料。这似乎应该很简单,但到目前为止,我只能想出低效的方法,比如:
using Microsoft.VisualBasic.FileIO;
var csvParser = new TextFieldParser(new StringReader(strCsvLine));
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
有没有好的方法可以让它更高效、更不难看?我将处理大量的字符串,所以我不想支付以上所有的费用。谢谢
这里有一个经过轻度测试的语法分析器,用于处理报价
public List<string> Parse(string line)
{
var columns = new List<string>();
var sb = new StringBuilder();
bool isQuoted = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
// If the current character is a double quote
if (c == '"')
{
// If we're not inside a quoted section, set isQuoted to true
if (!isQuoted && sb.Length == 0)
{
isQuoted = true;
}
else if (isQuoted && i + 1 < line.Length && line[i + 1] == '"') // Check for escaped double quotes
{
sb.Append('"');
i++; // Skip the next quote
}
else if (isQuoted) // If the next character is not a double quote, set isQuoted to false
{
isQuoted = false;
}
else // Not a quoted string
{
sb.Append('"');
}
continue;
}
// If the current character is a comma and we're not inside a quoted section, add the column and clear the StringBuilder
if (!isQuoted && c == ',')
{
columns.Add(sb.ToString());
sb.Clear();
continue;
}
// Append the character to the current column
sb.Append(c);
}
// Add the last column
columns.Add(sb.ToString());
return columns;
}