2013-04-26 39 views
0

我正在使用Visual Studio.net,Visual Basic,并且我有一个问题。 如果我有一个字符串中有很多行,获取某行内容的最佳方法是什么? E.g如果字符串如下:获取字符串中的一行内容

Public Property TestProperty1 As String 
    Get 
     Return _Name 
    End Get 
    Set(value As String) 
     _Name = value 
    End Set 
End Property 

什么是让2号线(“GET”)的内容,最好的办法?

回答

0

这取决于你的意思是“最好的”。

最简单,但效率最低,是将字符串分割成线,让他们中的一个:

Dim second As String = text.Split(Environment.NewLine)(1) 

最有效的将是找到字符串中的换行,并得到使用Substring行,但需要更多的代码:

Dim breakLen As Integer = Environment.Newline.Length; 
Dim firstBreak As Integer = text.IndexOf(Environment.Newline); 
Dim secondBreak As Integer = text.IndexOf(Environment.NewLine, firstBreak + breakLen) 
Dim second As String = text.Substring(firstBreak + breakLen, secondBreak - firstBreak - breakLen) 

要得到任何线,而不仅仅是第二,你,直到你得到正确的需要通过线更加代码回路。

1

最简单的是使用ElementAtOrdefault,因为您不需要检查集合是否有这么多项目。它会返回Nothing则:

Dim lines = text.Split({Environment.NewLine}, StringSplitOptions.None) 
Dim secondLine = lines.ElementAtOrDefault(1) ' returns Nothing when there are less than two lines 

注意,索引是从零开始的,因此,我已经使用ElementAtOrDefault(1)得到第二行。

这是不LINQ方法:

Dim secondLine = If(lines.Length >= 2, lines(1), Nothing) ' returns Nothing when there are less than two lines 
相关问题