简体   繁体   中英

Get the contents of a line in a string

I am using Visual Studio.net, Visual Basic and I have a question. If I have a string that has many lines in it, what is the best way to get the contents of a certain line? Eg If the string is as follows:

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

What is the best way to get the contents of line 2 ("Get")?

The simplest is to use ElementAtOrdefault since you don't need to check if the collection has so many items. It would return Nothing then:

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

Note that an index is zero-based, hence i have used ElementAtOrDefault(1) to get the second line.

This is the non-linq approach:

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

That depends on what you mean by "best".

The easiest, but least efficient, is to split the string into lines and get one of them:

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

The most efficient would be to locate the line breaks in the string and get the line using Substring , but takes a bit more code:

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)

To get any line, and not just the second, you need even more code to loop through the lines until you get to the right one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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