简体   繁体   English

使用递归反转字符

[英]Reversing characters using recursion

I can achieve reversing each word in a string and keep the order as well, but I believe it can be done quicker using recursion. 我可以实现反转字符串中的每个单词并保持顺序不变,但是我相信使用递归可以更快地完成。 At the moment I'm going through each character and flipping it, its not the best as it can be slow when the string is long. 目前,我正在浏览每个字符并将其翻转,这并不是最好的,因为当字符串较长时,它可能会变慢。 I'm working on an encryption algorithm if you want to know... 如果您想知道的话,我正在研究一种加密算法...

Example: 473hTml je31%@31# 示例:473hTml je31%@ 31#

This would result to: lmTh374 #13@%13ej 这将导致:lmTh374#13 @%13ej

Any guidance or a good read would be great. 任何指导或良好的阅读将是巨大的。

Don't use recursion: it won't be faster. 不要使用递归:它不会更快。 Reversing a string is not a problem that requires recursion. 反转字符串不是需要递归的问题。

Actually, VB.Net has a StrReverse function, so I would advise you to just use that (combine with String.Split to break your string into words, and String.Join to put them back together). 实际上,VB.Net具有StrReverse函数,所以我建议您只使用它(与String.Split组合以将字符串分解为单词,并与String.Join组合在一起)。

Also, don't roll your own crypto - at least, not for protecting anything serious. 另外, 请勿使用自己的加密货币 -至少,不是为了保护任何严重的东西。

I'm no vb expert, but something like this should be a good start. 我不是vb专家,但是这样的事情应该是一个好的开始。

public string reverseWord(string data) {
    if (data.length == 1) {
        return data;
    } else {
        return data.Concat(data.Substring(-1), reverseWord(data.Substring(1));
    }
}

Behold, the recursive BogoFlip! 看吧,递归的BogoFlip!

Module Module1
    Private rnd As New Random
    Dim str As String = "testing"

    Sub Main()
        Console.WriteLine(str & "     " & BogoFlip(str))
        Console.ReadLine()
    End Sub

    Public Function BogoFlip(originalString As String) As String
        Dim copy As String = originalString
        Dim flipped As String = ""
        Do Until copy.Length = 0
            Dim index As Integer = rnd.Next(copy.Length)
            flipped &= copy(index)
            copy = copy.Remove(index, 1)
        Loop
        If flipped = StrReverse(originalString) Then
            Return flipped
        Else
            Return BogoFlip(originalString)
        End If
    End Function
End Module

Please don't do this in real life... please please please please. 请不要在现实生活中这样做……请取悦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM