如何打乱字符串中的字符?

How to scramble characters in a string?

我正在编写一个读取文本文件的脚本。在 header 行之后,我读取了数据行。随着每条数据行被读入,AssetID 和 Description 列中的字符串值将被打乱。我在制表符分隔符上拆分了每一行。知道AssetID在数组位置1,Description在位置2,就可以拿到字符串了。

我想知道一个简单的打乱两个字符串的方法。这里有一些代码供参考。

P.S。现在我对循环进行了评论,以便我可以在第一行 header 上测试 "scrambling" 以确保它在我对整个项目实施它之前有效。

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("AssetImport.txt", ForReading)
Set objFile2 = objFSO.CreateTextFile("\newnewnew.txt")

Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine

    arrFields = Split(strLine, vbTab)

    If (UBound(arrFields) = 1) Then
        'script to write header lines here
        objFile2.WriteLine arrFields(0)
    Else
        'scramble AssetID and Description Columns, then write
        Randomize
        objFile2.WriteLine arrFields(0)
        arrFields(1) = Scramble(arrFields(1))
        objFile2.WriteLine arrFields(1)
        objFile2.WriteLine arrFields(2)
        objFile2.WriteLine arrFields(3)
        objFile2.WriteLine arrFields(4)
        arrFields(5) = Scramble(arrFields(5))
        objFile2.WriteLine arrFields(5)
        objFile2.WriteLine arrFields(6)
    End If
Loop

objFile.Close
objFile2.Close

Function Scramble(s)
    Dim i, j, n
    Dim temp, shuffled

    n = Len(s)
    ReDim shuffled(n - 1)
    For i = 1 To n
        shuffled(i - 1) = Mid(s, i, 1)
    Next

    For i = 0 To n - 2
        j = i + Int((n - i) * Rnd())
        temp = shuffled(i)
        shuffled(i) = shuffled(j)
        shuffled(j) = temp
    Next
    Scramble = Join(shuffled, "")

结束函数

我可能会这样做:

  1. 用字符串的字符填充字典,使用字符位置作为键。

    s = "..."   'string to scramble
    
    Set d = CreateObject("Scripting.Dictionary")
    For n = 1 To Len(s)
        d(n) = Mid(s, n, 1)
    Next
    
  2. 创建一个数组,其大小与字典中 key/value 对的数量相同。

    ReDim a(UBound(d.Keys))
    
  3. 选择一个随机键并将相应的项目放入数组的下一个空闲槽中,然后删除 key/value 对。重复直到所有字符都被移动。

    Randomize
    For n = 0 To UBound(a)
        keys  = d.Keys
        index = Int((UBound(keys) + 1) * Rnd)  'pick random key
        a(n)  = d(keys(index))                 'copy corresponding value to array
        d.Remove(keys(index))                  'remove key/value pair
    Next
    

    使用 keys 数组,以便可以通过(随机)索引选择剩余的键之一。

  4. 将数组连接回一个字符串:

    scrambled = Join(a, "")
    

您可以对字符串的字符进行 Fisher-Yates 随机播放:

Function Scramble(s)
    'Performs a Fisher-Yates Shuffle on the characters in the string
    'Assumes that Randomize has been called

    Dim i, j, n
    Dim temp, shuffled

    n = Len(s)
    ReDim shuffled(n - 1)
    For i = 1 To n
        shuffled(i - 1) = Mid(s, i, 1)
    Next

    'now do Fisher-Yates:
    For i = 0 To n - 2
        j = i + Int((n - i) * Rnd())
        temp = shuffled(i)
        shuffled(i) = shuffled(j)
        shuffled(j) = temp
    Next
    Scramble = Join(shuffled, "")

End Function

'test script:

Randomize
s = InputBox("Enter a word to be scrabled")
MsgBox Scramble(s)