递归扭转字符串C#
问题描述:
我不知道我不想直接回答我想知道我怎么能。 非常感谢提前。递归扭转字符串C#
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a word or sentence to be reversed: ");
string str = Console.ReadLine();
Console.WriteLine("**********");
Console.WriteLine("Your input is: ");
Console.WriteLine(str);
Console.ReadLine();//to give a little bit space between the outputs
Console.WriteLine("************");
Console.WriteLine("And it will be reversed as : ");
//call the Recursive Function in the class Recursive
str = Recursive.Recursive_Func(str);
Console.WriteLine(str);
Console.ReadLine();
}
}
我们使用子串从n-1的索引与该第一索引,其是字符串中打印字符串 中和结束它[0]。
class Recursive
{
public static string Recursive_Func(string str)
{
if (str.Length <= 1) //the program base case
{
return str;
}
else
{
return Recursive_Func(str.Substring(1)) + str[0];
}
}
}
答
你的实现是天真和缓慢的,但它是递归的,它的工作原理。下面的执行字符串转换成字符数组,使用递归辅助方法来扭转就地的字符,并且反转数组转换回字符串:
class Recursive
{
public static string StrRev(string s)
{
if (string.IsNullOrEmpty(s)) return s;
var a = s.ToCharArray();
return new string(CharArrRev(a, 0, a.Length - 1));
}
private static char[] CharArrRev(char[] a, int i, int j)
{
if (i >= j) return a;
var c = a[i]; a[i] = a[j]; a[j] = c;
return CharArrRev(a, i + 1, j - 1);
}
}
通常可以推测的问题是“如何能我修理了我的破碎程序?“据我所知,该程序是正确的。它使用递归来反转一个字符串。你真正的问题是什么?你怎么能*什么*? –
看到这个:[反转字符串的最佳方式](https://*.com/questions/228038/best-way-to-reverse-a-string) – Jimi