我正在尝试读取用逗号分隔的文本文件中的数据。我的问题是,我的一个数据块中有一个逗号。文本文件的示例如下:
a, b, "c, d", e, f.
我希望能够在c
和d
之间使用逗号并将其更改为分号,以便我仍然可以使用string.Split()
方法。
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine ()) != null) {
bool firstQuote = false;
for (int i = 0; i < line.Length; i++)
{
if (line [i] == '"' )
{
firstQuote = true;
}
else if (firstQuote == true)
{
if (line [i] == '"')
{
break;
}
if ((line [i] == ','))
{
line = line.Substring (0, i) + ";" + line.Substring (i + 1, (line.Length - 1) - i);
}
}
}
Console.WriteLine (line);
}
我遇到了问题。而不是生产
a, b, "c; d", e, f
正在制作
a, b, "c; d"; e; f
它用分号替换以下所有逗号而不是引号中的逗号。任何人都可以帮我修复现有的代码吗?
答案 0 :(得分:2)
基本上,如果您发现结束"
,您就会认出它,因为这是一个开场白。
更改行:
firstQuote = true;
到
firstQuote = !firstQuote;
它应该有用。
答案 1 :(得分:0)
点击第二个引号后,您需要将firstquote重置为false。
else if (firstQuote == true) {
if (line [i] == '"') {
firstquote = false;
break;
}
答案 2 :(得分:0)
这是一个获得所需结果的简单应用程序
static void Main(string[] args)
{
String str = "a,b,\"c,d\",e,f,\"g,h\",i,j,k,l,\"m,n,o\"";
int firstQuoteIndex = 0;
int secodQuoteIndex = 0;
Console.WriteLine(str);
bool iteration = false;
//String manipulation
//if count is even then count/2 is the number of pairs of double quotes we are having
//so we have to traverse count/2 times.
int count = str.Count(s => s.Equals('"'));
if (count >= 2)
{
firstQuoteIndex = str.IndexOf("\"");
for (int i = 0; i < count / 2; i++)
{
if (iteration)
{
firstQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
}
secodQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
string temp = str.Substring(firstQuoteIndex + 1, secodQuoteIndex - (firstQuoteIndex + 1));
firstQuoteIndex = secodQuoteIndex + 1;
if (count / 2 > 1)
iteration = true;
string temp2= temp.Replace(',', ';');
str = str.Replace(temp, temp2);
Console.WriteLine(temp);
}
}
Console.WriteLine(str);
Console.ReadLine();
}
如有疑问请随时提出
答案 3 :(得分:0)
string line = "a,b,mc,dm,e,f,mk,lm,g,h";
string result =replacestr(line, 'm', ',', ';');
public string replacestr(string line,char seperator,char oldchr,char newchr)
{
int cnt = 0;
StringBuilder b = new StringBuilder();
foreach (char chr in line)
{
if (cnt == 1 && chr == seperator)
{
b[b.ToString().LastIndexOf(oldchr)] = newchr;
b.Append(chr);
cnt = 0;
}
else
{
if (chr == seperator)
cnt = 1;
b.Append(chr);
}
}
return b.ToString();
}