-2

我有一个包含文本行的文本文件,如果下一行满足例如条件,我正在尝试将某行添加到列表框中

如果该行以 # 开头,则添加该行,如果下一行以 @ 开头,之后的所有行以 @ 开头

#add this line
@add this line
@add this line
@add this line
#dont add because the next line is not a @
#dont add because the next line is not a @
#dont add because the next line is not a @
#dont add because the next line is not a @
#add this line
@add this line
@add this line
#dont add because the next line is not a @
#add this line
@add this line  
#add this line
@add this line

希望这使场景任何帮助都会很棒

4

1 回答 1

3

使用 String 的 StartsWith 方法http://msdn.microsoft.com/en-us/library/system.string.startswith.aspx

你的整个功能就像

var lines = File.ReadAllLines(yourpath);
var resultLines = new List<string>();
bool adding = false;
for(int i=0;i<lines.Length;i++)
{
    var line = lines[i];
    if((line.StartsWith("#") && i < lines.Length-1 && lines[i+1].StartsWith("@"))
       || adding && line.StartsWith("@"))
        adding = true;
    else if(i < lines.Length-1 && !lines[i+1].StartsWith("@"))
        adding = false;
    if(adding)
        resultLines.Add(line);
}
于 2012-08-26T20:08:39.683 回答