2017-11-25 144 views
-4

我不知道我不想直接回答我想知道我怎麼能。 非常感謝提前。遞歸扭轉字符串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]; 
     } 
    } 
} 
+0

通常可以推測的問題是「如何能我修理了我的破碎程序?「據我所知,該程序是正確的。它使用遞歸來反轉一個字符串。你真正的問題是什麼?你怎麼能*什麼*? –

+1

看到這個:[反轉字符串的最佳方式](https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string) – Jimi

回答

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); 
    } 
}