/// <summary>
///ParseLine 的测试
///</summary>
[TestMethod()]
public void ParseLineTest()
{
Core target = new Core(); // TODO: 初始化为适当的值
string src = "1,ab ,c,\"\"\",e,f,g,\"\",\",smile,go,\"\"\",e1,f,g,\"\",\"";
List<string> expected =new List<string>();
//expected.Add("1,ab ,c,") ;
//expected.Add("\",e,f,g,\",");
//expected.Add(",smile,go");
expected.Add("1") ;
expected.Add("ab ");
expected.Add("c");
expected.Add("\",e,f,g,\",");
expected.Add("smile");
expected.Add("go");
expected.Add("\",e1,f,g,\",");
//expected.Add("\",e,f,g,\",");
//expected.Add(",smile,go");
List<string> actual;
actual = target.ParseLine(src);
for(int i=0;i<expected.Count;i++)
{
Assert.AreEqual(expected[i], actual[i]);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace CSVParser
{
public class Core
{
public List<string> ParseLine(string src)
{
List<String> r = new List<string>();
bool inBlock = false;
StringBuilder sb = new StringBuilder();
string rowBlock = string.Empty;
using (StringReader sr = new StringReader(src))
{
int val = sr.Read();
char nextChar = (char)sr.Peek();
while (val > 0)
{
char c = (char)val;
int nextVal = sr.Peek();
nextChar = (char)nextVal;
if (!inBlock)
{
if (c == '\"')
{
string[] list = sb.ToString().Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
foreach (string cell in list)
{
r.Add(cell);
}
sb.Length = 0;
inBlock = true;
}
else
{
sb.Append(c);
}
}
else
{
if (c == '\"' && nextChar == '\"')
{
c = (char)sr.Read();
sb.Append(c);
}
else if (c == '\"' &&
(nextChar == ','
||nextVal==-1
)
)
{
r.Add(sb.ToString());
sb.Length = 0;
inBlock = false;
}
else
{
sb.Append(c);
}
}
val = sr.Read();
}
if (sb.Length > 0)
{
string[] list = sb.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string cell in list)
{
r.Add(cell);
}
}
}
return r;
}
}
}