Results 1 to 3 of 3

Thread: [RESOLVED] Getting the contents of a certain line of a string

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2008
    Posts
    1,260

    Resolved [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")?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Getting the contents of a certain line of a string

    vb.net Code:
    1. ''' <summary>
    2. ''' Gets a single line from some text.
    3. ''' </summary>
    4. ''' <param name="text">
    5. ''' The original text.
    6. ''' </param>
    7. ''' <param name="index">
    8. ''' The zero-based index of the line to return.
    9. ''' </param>
    10. ''' <returns>
    11. ''' A <b>String</b> containing the specified line if it exists; otherwise, a null reference (<b>Nothing</b> in Visual Basic).
    12. ''' </returns>
    13. ''' <remarks>
    14. ''' The text is split preferentially on CR-LF pairs but also splits on lone LFs.
    15. ''' </remarks>
    16. Private Function GetLine(text As String, index As Integer) As String
    17.     Return text.Split({ControlChars.CrLf, ControlChars.Lf},
    18.                       StringSplitOptions.None).
    19.                 Skip(index).
    20.                 FirstOrDefault()
    21. 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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2008
    Posts
    1,260

    Re: Getting the contents of a certain line of a string

    Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width