Search code examples
vb.netstringforeachstring-parsingblank-line

String Parsing code breaks on vblf


I read through the lines of a text file but break on blank lines.

Using sr As New StreamReader(openFileDialog1.OpenFile())

    Dim text As [String] = sr.ReadToEnd()
    Dim lines As String() = text.Split(vbCrLf)
    For Each line As String In lines

        Dim cleanline = line.Trim()
        Dim words As String() = cleanline.Split(" ")
        For Each word As String In words
            If word.StartsWith("a", True, Nothing) OrElse word.StartsWith("e", True, Nothing) OrElse word.StartsWith("i", True, Nothing) OrElse word.StartsWith("o", True, Nothing) OrElse word.StartsWith("u", True, Nothing) OrElse word.StartsWith("y", True, Nothing) Then
                System.Console.Write(word & "ay ")
            Else
                Dim mutated As String = word.Substring(1, word.Length - 1)
                mutated = mutated & word.Substring(0, 1) & "yay "
                System.Console.Write(mutated)
            End If
        Next
        System.Console.Write(vbLf)

    Next
End Using

I am using this input.

I get this error:

enter image description here

What should I change to prevent this runtime error and continue processing?


Solution

  • you should do something like this to ensure that you don't have that error:

    ...
    For Each word As String In words
        If (word.Equals("")) Then
            Continue For
        End If
    ...
    

    This will ensure you never attempt to translate an empty string