tags:

views:

198

answers:

3

i am trying to split a string up into separate lines with the following code, but for some reason it is also removing the spaces in the string.

Dim calculationText As String
calculationText = File.ReadAllText(fileName)

Dim fields() As String
fields = calculationText.Split(vbCrLf)

when i am in debugger mode, i look at fields, and every element has a line of the string but all the spaces and tabs are removed.

any reason for this?

A: 

Gotta say I've never seen it do that, and I've used String.Split extensively. Are they really really gone, or is it a trick of the debugger?

There's not actually any .Split method that takes one string as the parameter, so the VB compiler would be doing "things" behind the scenes to pick a different overload. To try and force the correct overload, you could try calculationText.Split(vbCrLf.ToCharArray()). I doubt it will help, but you never know :-)

Dan F
+2  A: 

If you are reading from a file, can you use:

    Sub Main()
    Dim fields As New List(Of String)

    ' read file into list
    Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(filename)
        Try
            Do While sr.Peek() >= 0
                fields.Add(sr.ReadLine())
            Loop
        Finally
            If sr IsNot Nothing Then sr.Close()
        End Try
    End Using

    ' check results
    For Each line As String In fields
        Console.WriteLine(line)
    Next
End Sub
Bob
Doh.. We posted this solution at the same time. :-) I'll remove mine because you actually have a code sample.
Jesse Weigert
Um-- he could do this in a one-liner
Joel Coehoorn
+1  A: 

How 'bout:

Dim fields() As String = File.ReadAllLines(fileName)

As for why string.Split() is doing weird things...

vbCrLf is a string, and there's not an overload for string.split that accepts a single string parameter. If he were to turn on Option Explicit it wouldn't even compile, but since it's off, vbCrLf can be interpreted as an array of characters. And in this code, that's exactly what happens:

Sub Main()
    Dim z As String = "The quick brown" & vbCrLf & " fox jumps over the lazy dogs."
    Dim a() As String = z.Split(vbCrLf)
    For Each c As String In a
        Console.WriteLine(c)
    Next
    Console.ReadKey(True)
End Sub

You'll see two line breaks between the 1st and 2nd parts of that string. Something else is stripping out the spaces. Can you share the larger code block?

Joel Coehoorn
Dan F