字符串反转__StringReverse

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    /// <summary>
    /// 字符串反转
    /// </summary>
    public class StringReverse
    {

       publicStringReverse()
        {
            string a = "abcdefg";
            string expected = "gfedcba";


            Console.WriteLine(string.Equals(expected, StringReverse.ReverseByArray(a)));
            Console.WriteLine(string.Equals(expected, StringReverse.ReverseByStringBuilder(a)));
            Console.WriteLine(string.Equals(expected, StringReverse.ReverseByStringBuilder2(a)));
            Console.WriteLine(string.Equals(expected, StringReverse.ReverseByStack(a)));
            Console.WriteLine(string.Equals(expected, StringReverse.ReverseByRecursive(a)));
            Console.WriteLine(string.Equals(expected, StringReverse.ReverseByLinq(a)));

            Console.ReadLine();
        }



        /// <summary>
        /// 使用 Array.Reverse() 方法
        /// </summary>
        public static string ReverseByArray(string str)
        {
            char[] c = str.ToCharArray();
            Array.Reverse(c);

            return new string(c);
        }


        /// <summary>
        /// System.Enumerable 里提供了默认的 Reverse扩展方法,
        /// 我们可以基于该方法来对 String类型进行扩展
        /// </summary>
        public static string ReverseByLinq(string str)
        {
            return new string(str.Reverse().ToArray());
        }


        /// <summary>
        /// 使用 StringBuilder
        /// </summary>
        public static string ReverseByStringBuilder(string str)
        {
            StringBuilder builder = new StringBuilder(str.Length);
            for ( int i = str.Length - 1; i >= 0; i--)
            {
                builder.Append(str[i]);
            }

            return builder.ToString();
        }


        /// <summary>
        /// 栈是一个值类型的数据结构。
        /// 我们可以使用它后进先出的特性来对数组进行反转。
        /// 先将数组所有元素压入栈,然后再取出,顺序很自然地就与原先相反了
        /// </summary>
        public static string ReverseByStack(string str)
        {
            Stack<char> stack = new Stack<char>();
            foreach ( var item in str)
            {
                stack.Push(item);
            }

            char[] c = new char[str.Length];
            for ( int i = 0; i < str.Length; i++)
            {
                c[i] = stack.Pop();
            }

            return new string(c);
        }


        /// <summary>
        /// 使用委托,还可以使代码变得更加简洁
        /// </summary>
        public static string ReverseByRecursive(string str)
        {
            Func<string, string> f = null;
            f = s => s.Length > 0 ? f(s.Substring(1)) + s[0] : "";

            return f(str);
        }

    }
}
  

 

posted @ 2016-07-29 00:26  茗::流  阅读(1620)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。