[RESOLVED] Getting the contents of a certain line of a string
If I have a string that has many lines in it, what is the best way to get the contents of a certain line?
E.g If the string is as follows:
Code:
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")?
Re: Getting the contents of a certain line of a string
vb.net Code:
''' <summary>
''' Gets a single line from some text.
''' </summary>
''' <param name="text">
''' The original text.
''' </param>
''' <param name="index">
''' The zero-based index of the line to return.
''' </param>
''' <returns>
''' A <b>String</b> containing the specified line if it exists; otherwise, a null reference (<b>Nothing</b> in Visual Basic).
''' </returns>
''' <remarks>
''' The text is split preferentially on CR-LF pairs but also splits on lone LFs.
''' </remarks>
Private Function GetLine(text As String, index As Integer) As String
Return text.Split({ControlChars.CrLf, ControlChars.Lf},
StringSplitOptions.None).
Skip(index).
FirstOrDefault()
End Function
If the specified line is empty then that will return String.Empty while if the specified line doesn't exists, e.g. the text contains two lines and you specify 10 as the index, it will return Nothing. That could also be implemented as an extension method and called directly on any String.
Re: Getting the contents of a certain line of a string