0

我有 C# 的问题。

我正在编写代码来搜索文本文件,直到找到某个单词,然后代码应该移动三行并读取第四行,然后继续搜索以再次找到某个单词。现在我不知道如何通过文件(向前和向后)导航到我想要的行。

有人可以帮忙吗?

4

3 回答 3

1

你可以这样做:

var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
    //Find the word the first time
    if(!foundFirstTime && text[i].Contains("word"))
    {
        //Skip 3 lines - and continue
        i = Math.Min(i+3, text.Length-1);
        foundFirstTime = true;
    }

    if(foundFirstTime && text[i].Contains("word"))
    {
        //Do whatever!
    }
}
于 2013-05-23T16:25:32.697 回答
0
// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
                    select lines).ToList<string>();

for (int i = 0; i < query.Count; i++)
{
    if (query[i].Contains("TextYouWant"))
    {
        i = i + 3;
    }
}
于 2013-05-23T16:28:04.610 回答
0

您的要求表明您正在搜索特定的单词。如果这是真的并且您不是在寻找特定的字符串,那么检查的答案是错误的。相反,您应该使用:

string[] lines = System.IO.File.ReadAllLines("File.txt");

int skip = 3;

string word = "foo";

string pattern = string.Format("\\b{0}\\b", word);

for (int i = 0; i < lines.Count(); i++)
{
    var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);

    System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));

    if (match) i += skip;


}

如果您使用 string.contains 方法并且您正在搜索的单词是“man”,而您的文本在某处包含“mantle”和“manual”,则 string.contains 方法将返回 true。

于 2013-05-24T11:08:06.203 回答