随机字符添加到字符串

时间:2018-04-18 21:53:55

标签: vbscript

我试图在字符串的末尾添加一组随机数字。我还在学习VBS的基础知识,但这真的骗过我,我似乎无法在网上找到任何东西。

我试过了:

string2 = "hello" + (Rnd() * Len(VALID_TEXT)) + 1

x = rnd*10
string2 = "hello" + x

我做错了什么?

2 个答案:

答案 0 :(得分:0)

&是字符串连接字符。 +是一个旧的兼容性concat字符,如果混合使用文本和数字,则会出错。仅使用+进行数学运算。

答案 1 :(得分:0)

所有随机数生成器都依赖于底层算法,通常由所谓的种子数来提供。您可以使用Randomize语句创建新的种子编号,以确保随机数不遵循可预测的模式。

要获取随机数,仅使用rnd是不够的,因为您将一次又一次地获得相同的随机数。您必须使用randomize来完成任务,如下所示:

Dim strTest:strTest = "Hello"
Dim intNoOfDigitsToAppend:intNoOfDigitsToAppend = 5
Randomize
Msgbox "String before appending: " & strTest
strTest = fn_appendRandomNumbers(strTest,intNoOfDigitsToAppend)
Msgbox "String before appending: " & strTest

function fn_appendRandomNumbers(strToAppend,intNoOfRandomDigits)
    Dim i
    for i=1 to intNoOfRandomDigits
        strToAppend= strToAppend & int(rnd*10)           'rnd gives a random number between 0 and 1, something like 0.8765341. Then, we multiply it by 10 so that the number comes in the range of 0 to 9. In this case, it becomes 8.765341. After that, we use the int method to truncate the decimal part so that we are only left with the Integer part. In this case, 765341 is truncated and we are left with only the integer 8
    next
    fn_appendRandomNumbers = strToAppend
end function

<强> Reference 1

<强> Reference 2