开发者

All i need to know that the method reverseString takes in an array of char or a normal String?

开发者 https://www.devze.com 2023-01-31 00:56 出处:网络
Write a recursive method stringRev开发者_JAVA技巧erse that takes a character array containing a string as an argument and prints the string backwards. [Hint: Use String method toCharArray, which takes

Write a recursive method stringRev开发者_JAVA技巧erse that takes a character array containing a string as an argument and prints the string backwards. [Hint: Use String method toCharArray, which takes no arguments, to get a char array containing the characters in the String.]


Here you go : For returning the reversed string, you would use:

public static char[] StringReverse(char[] x , int startindex)
{
    int p = x.length;
    if(startindex < p/2)
    {
        char temp = x[startindex];
        x[startindex] = x[x.length - startindex-1];
        x[x.length - startindex-1] = temp;
        return StringReverse(x , startindex+1);
    }
    else
    {
        return x;
    }
}

For directly printing it, go for this

public static void StringReverse(char[] x , int startindex)
{
    int p = x.length;
    if(startindex < p/2)
    {
        char temp = x[startindex];
        x[startindex] = x[x.length - startindex-1];
        x[x.length - startindex-1] = temp;
        StringReverse(x , startindex+1);
    }
    else
    {
        System.out.println(x);
    }
}

For example, for following input

new String("Hello world").toCharArray()

The output will be

run:
dlrow olleH
BUILD SUCCESSFUL (total time: 0 seconds)


        char[] pStringReverse(char[] array, int index)
        {
            char tmp = array[index];
            array[index] = array[array.Length - index - 1];
            array[array.Length - index - 1] = tmp;
            index++;
            if (index >= array.Length / 2)
                return pStringReverse(array, index);
            return array;
        }
        string stringReverse(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            return new string(pStringReverse(str.ToCharArray(), 0));
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消