我已经尝试了几种不同的方法,但都不能正常工作,所以我只是想找个人直接告诉我怎么做。我想让我的应用程序读入一个基于OpenFileDialog的文件。
当文件被读入时,我想遍历它并运行这个函数,该函数使用Linq将数据插入到我的数据库中。
objSqlCommands.sqlCommandInsertorUpdate然而,我想要遍历字符串,计算找到的",“的数量。当数字达到4时,我只想获取遇到的字符,直到下一个",”,并这样做,直到文件结束。有人能告诉我如何做到这一点吗?
基于这里给出的答案,我的代码现在看起来像这样
File.ReadAllText(ofd.FileName).Replace(Environment.NewLine,fileText = string ",");
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();
foreach (char c in fileText.ToArray())
{
idx++;
if (c == ',')
{
counter++;
}
if (counter == 4)
{
string x = fileText.Substring(idx);
foo.Add(fileText.Substring(idx, x.IndexOf(',')));
counter = 0;
}
}
foreach (string s in foo)
{
objSqlCommands.sqlCommandInsertorUpdate("INSERT", s);//laClient[0]);
}然而,我在foo.add函数调用中得到了一个“长度不能小于0”的错误,你有什么想法吗?
发布于 2013-08-06 16:34:30
这是一个有点老生常谈的例子。您可以将文件中的整个文本作为单个字符串传递给它。
string str = "1,2,3,4,i am some text,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();
foreach (char c in str.ToArray())
{
idx++;
if (c == ',')
{
counter++;
}
if (counter == 4)
{
string x = str.Substring(idx);
foo.Add(str.Substring(idx, x.IndexOf(',')));
counter = 0;
}
}
foreach(string s in foo)
{
Console.WriteLine(s);
}
Console.Read();打印:
i am some text91317发布于 2013-08-06 16:15:45
File.ReadAllText将文本文件读取为字符串,然后Split将该字符串转换为逗号分隔的数组:
File.ReadAllText(OpenDialog.FileName).Split(',')[4]如果您有多条线路,请使用:
File.ReadAllLines(OpenDialog.FileName).Select(l => l.Split(',')[4])这将提供一个IEnumerable<string>,其中每个字符串都包含文件一行中所需的部分
发布于 2013-08-06 16:34:42
正如Raidri在他的回答中指出的那样,String.Split绝对是你的朋友。要抓住每五个单词,你可以尝试这样的东西(未测试):
string fileText = File.ReadAllText(OpenDialog.FileName).Replace(Environment.NewLine, ",");
string words[] = fileText.Split(',');
List<string> everFifthWord = new List<string>();
for (int i = 4; i <= words.Length - 1, i + 5)
{
everyFifthWord.Add(words[i]);
}上面的代码从OpenFileDialog中读取选定的文件,然后将每个换行符替换为",“。然后,它将字符串拆分为",",并从第五个单词开始,获取字符串中的每个第五个单词并将其添加到列表中。
https://stackoverflow.com/questions/18074789
复制相似问题