2012-08-26 101 views
-2

我有一个包含文本行的文本文件,我想一定行添加到一个列表框,如果下一行满足例如条件C#添加从文本文件行到一个列表框

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

#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 

希望启动,这使得现场的任何帮助将是巨大

+2

[什么都尝试过你?](http://whathaveyoutried.com) – GameScripting

+0

你为什么需要这样一个疯狂的滤波方案?!? –

回答

3

使用字符串的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); 
} 
+0

哇,这是丑陋的代码,但它的工作原来的问题是真正的丑陋。可能一些额外的,有名的变量可以减少一些混乱。 +1“,因为它完美地工作。 –

+0

谢谢你会试试看 –

相关问题