Search code examples
vb.netstringscramble

Better VB.NET String Scrambler?


I needed a function to take a string phrase and scramble it. So I wrote this, but I'm wondering if there is a more efficient/faster way to do it?

    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

Solution

  • Here's Plutonix's one-liner:

    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
    

    ...and here's an alternate version of your longer form:

    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