递归字符串反向函数 [英] recursive string reverse function

查看:55
本文介绍了递归字符串反向函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇而编写了一个递归字符串反向函数,但是那里的XOR有点问题.该函数的全部重点是不使用迭代器,这就是为什么它是递归函数的原因.这不是功课,只是好奇心.

writing a recursive string reverse function out of curiosity, but having a bit of problem with XOR there. The whole point of this function, is to not use iterator, which is why it is a recursive function. this is not homework, just curiosity.

    private static char[] ReverseNL(char[] arr, int index)
    {
        var len = arr.Length;
        if (index > 0)
            arr[len - index] ^= arr[index - 1];
        return index-- < 1 ? arr : ReverseNL(arr, index);
    }

它似乎弄乱了我字符串的第一部分

it seems to jamble the first part of my string

嘿,堆!"变成"I♫→A←E↨rehtyeeh"

"hey there stack!" becomes "I♫→A ←E↨reht yeh"

它总是混杂在短语的前半部分...

it is always the first half of the phrase that gets jumbled...

更新..

我想这里实际上并不需要XOR.所以使用了基本的赋值,也摆脱了回报.

i suppose XOR wasn't really needed here.. so used basic assignment, also got rid of return.

    private static void ReverseNL(char[] arr, int index) {
        var len = arr.Length;
        if (index > 0 && index > len / 2) {
            var c = arr[len - index];
            arr[len - index] = arr[index - 1];
            arr[index - 1] = c;
            index--;
            ReverseNL(arr, index);
        }
    }

推荐答案

如果要使用XOR和递归的解决方案,请尝试以下操作:

If you want a solution which uses XOR and recursion, try this:

private static void ReverseNL(char[] arr, int index)
{
    if (index <arr.Length/2)
    {
        arr[index] ^= arr[arr.Length - index-1];
        arr[arr.Length - index-1] ^= arr[index ];
        arr[index] ^= arr[arr.Length - index-1];
        ReverseNL(arr,++index);
    }
}

您不需要返回任何内容,因为所有操作都在数组中完成.当然,您可以删除XOR部分并交换元素,但这凉爽.;)

You don't need to return anything, since everything is done in the array. Of course you could just remove the XOR-part and just swap the elements, but this is much cooler. ;)

(索引应从0开始)

这篇关于递归字符串反向函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆