繁体   English   中英

获取字符串中的行的内容

[英]Get the contents of a line in a string

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

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

获取第2行(“获取”)内容的最佳方法是什么?

最简单的是使用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

这取决于你对“最佳”的意思。

最简单但效率最低的是将字符串拆分为行并获取其中一行:

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)

要获得任何一行,而不仅仅是第二行,你需要更多的代码来遍历这些行,直到你找到正确的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM