如何从文本文件中获取几行?

时间:2013-05-19 21:30:02

标签: c# string file text

我有一个文本文件:

hh
    Something sdf....
    one line 
    empty line
    other line
    goal 

    Something apf ee
    one line 
    goal 

List<String> goo = new List<String>();

System.IO.StreamReader file = new System.IO.StreamReader("text.txt");
while (file.EndOfStream != true)
{
    string s = file.ReadLine();
    if (s.Contains("Something"))
    {            
        goo.Add(s);
    }
}

我想在Something之后和goal之后获取所有行。 文件中有许多Somethinggoal。我应该使用数组或某些东西......?

3 个答案:

答案 0 :(得分:0)

这是元代码

Iterate over lines
    if line starts from "Something"
        ShouldAppend = true
    end

    if line starts from "goal"
        ShouldAppend = false
    end

    if ShouldAppend == true

        // append lines to string builder 
        // or add to list as you need

    end
end

答案 1 :(得分:0)

只需跟踪状态读数。从我所知道的,你有两种状态。当你想添加这条线时,你什么时候不想。如果你跟踪状态,那么你只需要在添加时检查状态。一个简单的,但不是最好的方式,因为它不是很强大,这样做的方式将是这样的:

    while (file.EndOfStream != true)
    {   
        bool addStuff = false;
        string s = file.ReadLine();
        if (s.Contains("Something"))
        {   
           addStuff = true;
        }else if (s.Contains("goal")){
           addStuff = false
        }

        if(addStuff){
            goo.Add(s);
        }
    }

警告这并不健全,因为它不会处理无效格式等等。这是为了指导您如何处理这个问题。

答案 2 :(得分:0)

我将提供LINQ风格的解决方案。首先,一个简单的辅助扩展方法,用于从IEnumerable<T>

中选择子范围
public static class EnumerableHelper
{
    public static IEnumerable<List<T>> GetWindows<T>(
        this IEnumerable<T> source,
        Func<T, bool> begin,
        Func<T, bool> end)
    {
        List<T> window = null;
        foreach (var item in source)
        {
            if (window == null && begin(item))
            {
                window = new List<T>();
            }
            if (window != null)
            {
                window.Add(item);
            }
            if (window != null && end(item))
            {
                yield return window;
                window = null;
            }
        }
    }
};

现在你可以像这样得到你感兴趣的文本窗口:

List<List<string>> windows = File.ReadLines("file.txt")
    .GetWindows(
        line => line.Contains("Something"),
        line => line.Contains("goal"))
    .ToList();

windows中的每个项目都是与单个“Something ... goal”对相对应的文本行列表。