我通读了一个文本文件的行但是在空行上打破了。
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
我正在使用this输入。
我收到此错误:
我应该更改什么来防止此运行时错误并继续处理?
答案 0 :(得分:2)
替换它:
System.Console.Write(vbLf)
有了这个:
Console.WriteLine()
For Each line As String In lines
If line.IsNullOrWhiteSpace() Then Exit For
答案 1 :(得分:1)
你应该做这样的事情,以确保你没有那个错误:
...
For Each word As String In words
If (word.Equals("")) Then
Continue For
End If
...
这将确保您永远不会尝试翻译空字符串
答案 2 :(得分:0)
首先,我将StringSplitOptions.None用于行和单词。它将删除空字符串拆分。
Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
然后我替换了If语句,该语句检查了 word .starsWith({vowels})及其Regex等价物。此外,您可以使用RegexOptions.IgnoreCase使其不区分大小写。 (导入Text.RegularExpressions)
If Regex.IsMatch(word, "^[aeiouy]", RegexOptions.IgnoreCase) Then
最后,我添加了一个If来检查word.Length>在尝试访问单词(1)之前为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