在C#中搜索关键字并将该行作为字符串输出

在C#中搜索关键字并将该行作为字符串输出,c#,.net,C#,.net,如何在文本文件中搜索字符串,例如#Test1,然后将其下方的行作为字符串输出,例如 Test.txt #Test1 86/100 #Test2 99/100 #Test3 13/100 因此,如果#Test2是搜索关键字,“99/200”将转换为字符串使用readline并搜索字符串(例如#Test1),然后使用下一行作为输入。正则表达式如何 如果正是上述文件格式。那么你可以用这个 1. read all lines till eof in an array. 2. now run a l

如何在文本文件中搜索字符串,例如#Test1,然后将其下方的行作为字符串输出,例如

Test.txt

#Test1
86/100

#Test2
99/100

#Test3
13/100

因此,如果#Test2是搜索关键字,“99/200”将转换为字符串

使用readline并搜索字符串(例如#Test1),然后使用下一行作为输入。

正则表达式如何

如果正是上述文件格式。那么你可以用这个

1. read all lines till eof in an array.
2. now run a loop and check if the string[] is not empty.
   Hold the value in some other array or list. 
   now you have items one after one. so whenever you use loop and use [i][i+1], 
   it will give you the test number and score.
希望这会有所帮助。

解析文件一次,将结果存储在字典中。然后查字典

var dictionary = new Dictionary<string, string>();
var lines = File.ReadLines("testScores.txt");
var e = lines.GetEnumerator();
while(e.MoveNext()) {
    if(e.Current.StartsWith("#Test")) {
        string test = e.Current;
        if(e.MoveNext()) {
            dictionary.Add(test, e.Current);
        }
        else {
            throw new Exception("File not in expected format.");
        }
    }
}  
等等


另外,从长远来看,我建议移动到数据库。

这应该可以帮助您:

        int lineCounter = 0;
        StreamReader strReader = new StreamReader(path);

        while (!strReader.EndOfStream)
        {
            string fileLine = strReader.ReadLine();
            if (Regex.IsMatch(fileLine,pattern))
            {
                Console.WriteLine(pattern + "found in line " +lineCounter.ToString());
            }
            lineCounter++;
        }

你试过什么?您在加载/处理文件或逻辑方面有问题吗?这两个问题都很简单(File.OpenText/ReadLine和一个简单的标志来记住最后一行是否以“#Text”开头就可以了),我同意-你在关键点上击败了我+1
        int lineCounter = 0;
        StreamReader strReader = new StreamReader(path);

        while (!strReader.EndOfStream)
        {
            string fileLine = strReader.ReadLine();
            if (Regex.IsMatch(fileLine,pattern))
            {
                Console.WriteLine(pattern + "found in line " +lineCounter.ToString());
            }
            lineCounter++;
        }