更好的 VB.NET 字符串扰码器?
Better VB.NET String Scrambler?
我需要一个函数来获取字符串短语并将其打乱。所以我写了这个,但我想知道是否有更多 efficient/faster 的方法来做到这一点?
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
这是 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
我需要一个函数来获取字符串短语并将其打乱。所以我写了这个,但我想知道是否有更多 efficient/faster 的方法来做到这一点?
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
这是 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