编写一个递归方法stringReverse,它将包含字符串的字符数组作为参数,然后向后打印字符串。 [提示:使用String方法toCharArray,它不带参数,获取包含String中字符的char数组。]
答案 0 :(得分:2)
你走了: 要返回反向字符串,您可以使用:
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;
}
}
要直接打印,请转到
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);
}
}
例如,用于跟随输入
new String("Hello world").toCharArray()
输出
run:
dlrow olleH
BUILD SUCCESSFUL (total time: 0 seconds)
答案 1 :(得分:0)
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));
}