string startIndex 不能大于字符串的长度。参数名称:vb.net 中的 startIndex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18859036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:05:39  来源:igfitidea点击:

startIndex cannot be larger than length of string. Parameter name: startIndex in vb.net

vb.netstringrandomsubstring

提问by user2784251

I have a piece of code that generates random characters. The problem is, every once in a while, it returns an error:
"startIndex cannot be larger than length of string. Parameter name: startIndex"

我有一段生成随机字符的代码。问题是,每隔一段时间,它就会返回一个错误:
“startIndex 不能大于字符串的长度。参数名称:startIndex”

How do I prevent this kind of error from happening?

我如何防止这种错误的发生?

Here's my code:

这是我的代码:

Friend Function gentCtrlChar()
    Dim ran As New Random
    Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim alpha2 As String = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
    Dim rdm As New Random
    Dim genChar As String = ""
    For i As Integer = 1 To 52
        Dim selChar As Integer = rdm.Next(1, 28)
        Dim selChar2 As Integer = rdm.Next(1, 28)
        genChar = genChar + "" + alpha.Substring(selChar, 1) + "" + alpha2.Substring(selChar2, 1)
        On Error Resume Next
        Exit For
    Next
    Return genChar
End Function

as you can see, I tried putting the "On Error Resume Next" hoping that somehow, this will take care of the error for me. But sadly, It doesn't do it's job. Or am I using it the wrong way or for the wrong situation?

如您所见,我尝试将“On Error Resume Next”放在后面,希望以某种方式解决我的错误。但遗憾的是,它并没有完成它的工作。还是我以错误的方式或在错误的情况下使用它?

Any help?

有什么帮助吗?

Thanks!

谢谢!

回答by BWS

this code:

这段代码:

Dim selChar As Integer = rdm.Next(1, 28)

will sometimes return a number that is longer (27 or 28) than the length of this string:

有时会返回一个比这个字符串的长度更长的数字(27 或 28):

Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  (only 26 characters long)

so, this is invalid when selChar is 26 or more.

因此,当 selChar 为 26 或更多时,这是无效的。

alpha.Substring(selChar, 1)

Easiest fix is:

最简单的修复方法是:

Dim selChar As Integer = rdm.Next(0, alpha.Length) 
Dim selChar2 As Integer = rdm.Next(0, alpha2.Length) 

回答by jcwrequests

Try this way. I think its cleaner and easy to understand. A - Z is the same as 65 - 90 on the ascii map so its very easy to convert an integer into a Char value. Then we just use the string builder to make this easier to read.

试试这个方法。我认为它更清晰易懂。A - Z 与 ascii 映射上的 65 - 90 相同,因此很容易将整数转换为 Char 值。然后我们只使用字符串构建器来使它更容易阅读。

Dim rdm As New Random
Dim genChar As New StringBuilder()
For i As Integer = 1 To 52
    Dim selChar As Char = Chr(rdm.Next(65, 90))
    Dim selChar2 As Char = Chr(rdm.Next(65, 90))
    genChar.Append(selChar)
    genChar.Append(selChar2)
Next
Return genChar.ToString