如何在字符串中加扰字符?

时间:2017-09-28 20:29:04

标签: string random vbscript scramble

我正在编写一个读取文本文件的脚本。标题行后,我读取数据行。在读入每个数据行时,将对AssetID和Description列中的字符串值进行加扰。我在制表符分隔符上拆分每一行。知道AssetID在数组位置1,而描述在位置2,我可以得到字符串。

我想知道一种简单的方法来扰乱这两个字符串。这是一些供参考的代码。

P.S。现在我评论了循环,以便我可以测试第一个标题行上的“加扰”,以确保它在我在整个项目中实现之前有效。

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, "")

结束功能

2 个答案:

答案 0 :(得分:2)

您可以对字符串的字符进行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)

答案 1 :(得分:0)

我可能会这样做:

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

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

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

    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, "")