字符串反向输出

这是网上看到的一道面试题,自己试着写了几种方法:

 

    class Program
    {
        static void Main()
        {

            string str1 = "hello";
            char[] c = str1.ToCharArray();
           

            //1.字符反转
            Array.Reverse(c);
            string str2 = new string(c);
            Console.WriteLine(str2);

            //2.反向输出字符

            for (int i = c.Length - 1; i >= 0; i--)
                Console.Write(c[i]);

 

            //3.递归

            Recursive(str1);
        }

 

        private static void Recursive(string s)
        {
            if (s.Length == 0)
                Console.Write(s);
            else
            {
                string last = s.Substring(s.Length - 1, 1);
                Console.Write(last);
                Recursive(s.Substring(0, s.Length - 1));
            }
        }
    }

你可能感兴趣的:(字符串反向输出)