为什么这个指数超出范围? (视觉基础)

Why is this index out of range? (Visual Basic)

           For k As Integer = 0 To (input.Length - 1)
                If input(input.Length - 1) <> " " Then
                    letter &= input(k)
                ElseIf input(k) = " " And ((k = 0) Or (input(k - 1) <> " ")) Then
                    For a As Integer = lastspace To k
                        letter &= input(a)
                    Next
           Next

字母和输入已变暗为字符串,输入等于 console.readline() 每次我 运行 这个程序,我都会在第一个 ElseIf 上得到一个 "IndexOutOfRangeException" 错误。我刚开始 VB 所以我不太确定这里出了什么问题,或者如何解决它。 我试图用 "k=0 or" 修复它,但它没有帮助。有什么想法吗?

当k=0时,输入(k - 1)导致数组下标为-1,超出范围

VB.NET 中的 Or 运算符不会短路表达式的计算。因此,当 k 为 0

时,您的 Or 不会阻止对 k-1 的评估

你应该使用

ElseIf input(k) = " " And ((k = 0) OrElse (input(k - 1) <> " ")) Then

来自 MSDN Or Operator

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

来自 MSDN OrElse Operator

A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression. If the result of the first expression evaluated determines the final result of the operation, there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve performance if the bypassed expression is complex, or if it involves procedure calls.