1

我通读了文本文件的行,但在空白行处中断。

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

我正在使用这个输入。

我收到此错误:

在此处输入图像描述

我应该改变什么来防止这个运行时错误并继续处理?

4

3 回答 3

2

替换这个:

System.Console.Write(vbLf)

有了这个:

Console.WriteLine()

For Each line As String In lines
   If line.IsNullOrWhiteSpace() Then Exit For
于 2013-11-19T19:42:39.923 回答
1

你应该做这样的事情来确保你没有那个错误:

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

这将确保您永远不会尝试翻译空字符串

于 2013-11-19T20:08:32.813 回答
0

首先,我将 StringSplitOptions.None 用于lineswords。它将删除空字符串拆分。

Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)

然后,我将检查 if单词.starsWith({vowels}) 的 If 语句替换为其 Regex 等效项。此外,您可以使用 RegexOptions.IgnoreCase 使其不区分大小写。(导入 Text.RegularExpressions)

If Regex.IsMatch(word, "^[aeiouy]", RegexOptions.IgnoreCase) Then

最后,在尝试访问 word(1) 之前,我添加了一个 If 来检查 word.Length > 0。

这是我的最终代码:

Using sr As New StreamReader(OpenFileDialog1.OpenFile())
    Dim text As String = sr.ReadToEnd()
    Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
    For Each line As String In lines
        Dim cleanline As String = line.Trim()
        Dim words As String() = cleanline.Split(New Char() {" "c}, StringSplitOptions.None)
        For Each word As String In words
            If Regex.IsMatch(word, "^[aeiouy]", RegexOptions.IgnoreCase) Then
                System.Console.WriteLine(word & "ay ")
            ElseIf word.Length > 0 Then
                Dim mutated As String = word(1) & word(0) & "yay "
                System.Console.WriteLine(mutated)
            End If
        Next
    Next
End Using
于 2013-11-21T10:55:55.977 回答