views:

56

answers:

2

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
A: 

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.

rerun
Cheers! I kind of knew this vaguely, was really looking for a good code example. But thanks!
bretddog
+3  A: 

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()
Dan Tao
Hmm.. nice idea. Thanks! :)
bretddog
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.
bretddog
+1 for showing the "AsReadOnly()"
Saif Khan
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..
bretddog