C#几种字符串反转方法

            static string Reverse1(string original)
            {
                char[] arr = original.ToCharArray();
                Array.Reverse(arr);
                return new string(arr);
            }

            static string Revease21(string original)
            {
                int length = original.Length;
                char[] arr = new char[length];
                for (int i = 0; i < (length & (~3)); i += 4)
                {
                    arr[i] = original[length - i - 1];
                    arr[i+1] = original[length - i - 2];
                    arr[i+2] = original[length - i - 3];
                    arr[i+3] = original[length - i - 4];
                }
                for (int i = length & (~3); i < length; i++)
                {
                    arr[i] = original[length - i - 1];
                }
                return new string(arr);
            }

            static string Revease22(string original)
            {
                int length = original.Length;
                char[] arr = new char[length];
                for (int i = 0; i < length; i++)
                {
                    arr[i] = original[length - i - 1];
                }
                return new string(arr);
            }

            static string Revease3(string original)
            {
                int length = original.Length;
                StringBuilder sb = new StringBuilder(length);
                for (int i = length-1; i >= 0; i--)
                sb.Append(original[i]);
                return sb.ToString();
            }

Revease1()代码最简洁,运行速度也最快,Revease21()和Revease22()其次,Revease3()最慢。可见.net framework中实现的ToCharArray()和Array.Revease()效率还是蛮高的^_^

 

你可能感兴趣的:(c#)