【问题标题】:Search for a keyword in C# and output the line as a string在 C# 中搜索关键字并将该行输出为字符串
【发布时间】:2011-09-25 15:03:45
【问题描述】:

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

Test.txt

#Test1
86/100

#Test2
99/100

#Test3
13/100

所以如果#Test2 是搜索关键字“99/200”将变成一个字符串

【问题讨论】:

  • 你试过什么?您在加载/处理文件或为此的逻辑 有问题吗?这两个问题都很简单(File.OpenText / ReadLine 和一个简单的标志来记住最后一行是否以“#Text”开头就可以完成这项工作)

标签: c# .net


【解决方案1】:

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

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.");
        }
    }
}  

现在你可以说

Console.WriteLine(dictionary["#Test1"]);

等等

此外,长期而言,我建议迁移到数据库。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我同意 - 你在 +1 键上打败了我
    【解决方案3】:

    如果上面正是文件格式。那你就可以用这个了

    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.
    

    希望这可能会有所帮助。

    【讨论】:

      【解决方案4】:

      正则表达式怎么样? here's a good example

      【讨论】:

        【解决方案5】:

        这应该为你做:

                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++;
                }
        

        【讨论】:

          猜你喜欢
          • 2019-09-17
          • 1970-01-01
          • 2020-12-11
          • 1970-01-01
          • 2011-09-03
          • 1970-01-01
          • 1970-01-01
          • 2014-12-08
          • 1970-01-01
          相关资源
          最近更新 更多