更好的VB.NET String Scrambler?

时间:2015-07-24 21:29:12

标签: vb.net string scramble

我需要一个函数来获取一个字符串短语并加扰它。所以我写了这个,但我想知道是否有更有效/更快的方法来做到这一点?

    Public Function Scramble(phrase As String) As String
    Dim rand As New Random()
    Dim newPhrase As String = ""
    Dim clist As New List(Of String)

    ' break phrase into characters and add to list
    For i As Integer = 1 To Len(phrase)
        clist.Add(Mid(phrase.ToLower(), i, 1))
    Next

    ' remove from list randomly and add to new string
    Do While clist.Count > 0
        Dim r As Integer = rand.Next(0, clist.Count)
        newPhrase &= clist(r)
        clist.RemoveAt(r)
    Loop

    Return newPhrase

End Function

1 个答案:

答案 0 :(得分:1)

这是Plutonix的单线:

Public Function Scramble(ByVal phrase As String) As String
    Static rand As New Random()
    Return New String(phrase.ToLower.ToCharArray.OrderBy(Function(r) rand.Next).ToArray)
End Function

...这里是你的长篇形式的替代版本:

Public Function Scramble(ByVal phrase As String) As String
    Static rand As New Random()
    Dim sb As New System.Text.StringBuilder
    Dim chars As New List(Of Char)(phrase.ToLower.ToCharArray)
    While chars.Count > 0
        Dim r As Integer = rand.Next(0, chars.Count)
        sb.Append(chars(r))
        chars.RemoveAt(r)
    End While
    Return sb.ToString
End Function