0

When I try to split a string into a string list where each element represents a line of the initial string, I get the "square" character, which I think is a linefeed or something, at the start of each line, except the first line. How can I avoid that? My code is as follows:

Dim strList as List(Of String)
If Clipboard.ContainsText Then 
  strList = Clipboard.GetText.Split(Environment.NewLine).ToList
End If

2 Answers 2

4

I find that a pretty reliable way to read the lines of a string is to use a StringReader:

Dim strList As New List(Of String)
Using reader As New StringReader(Clipboard.GetText())
    While reader.Peek() <> -1
        strList.Add(reader.ReadLine())
    End While
End Using

Maybe that's weird; I don't know. It's nice, though, because it frees you from dealing with the different ways of representing line breaks between different systems (or between different files on the same system).

Taking this one step further, it seems you could do yourself a favor and wrap this functionality in a reusable extension method:

Public Module StringExtensions
    <Extension()> _
    Public Function ReadAllLines(ByVal source As String) As IList(Of String)
        If source Is Nothing Then
            Return Nothing
        End If

        Dim lines As New List(Of String)
        Using reader As New StringReader(source)
            While reader.Peek() <> -1
                lines.Add(reader.ReadLine())
            End While
        End Using

        Return lines.AsReadOnly()
    End Function
End Module

Then your code to read the lines from the clipboard would just look like this:

Dim clipboardContents As IList(Of String) = Clipboard.GetText().ReadAllLines()
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I didn't expect to learn something that useful from this question. :) Really good stuff. I never made such extensions before, so will be a great tool for me to know this.
I must admit I don't see really what this "AsReadOnly" does.. But I'm also not used to work with "Interfaces", so I guess I have some study to do..
0

There is a carriage return and line feed on each of your lines. character 10 and character 13 combine them into a string and split and you will get what you need.

1 Comment

Cheers! I kind of knew this vaguely, was really looking for a good code example. But thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.