Requirement: If a string is specified, the string is reversed. For example, if "Welcome to caochao's blog!" is specified !", Output "! Golb s 'oahcoac ot emoclew ".
When you look at the question for the first time, you may think of a solution that traverses the string in reverse order, takes characters by bit, and then splices into a new string. The new string is the reversed string.CodeAs follows:
/// <Summary> // string reversal-stringbuilder implementation // </Summary> /// <Param name = "str"> </param> // <returns> </returns> Public static string reverseusingstringbuilder (string Str) {int length = Str. length; stringbuilder sb = new stringbuilder (length); For (INT I = length-1; I> = 0; I --) {sb. append (STR [I]);} return sb. tostring ();}
But in fact, there is still a simpler method, which is incredibly simple. When I see this method, I have to marvel at the completeness of the. NET Framework method. The Code is as follows:
/// <Summary> // string reversal-chararray implementation /// </Summary> /// <Param name = "str"> </param> // <returns> </returns> Public static string reverseusingchararray (string Str) {char [] arr = Str. tochararray (); array. reverse (ARR); return new string (ARR );}
But if you think about it, it may be faster, at least in principle. This method traverses both ends of the string and then exchanges values one by one. The Code is as follows:
/// <Summary> /// reverse string-XOR or implementation /// </Summary> /// <Param name = "str"> </param> /// <returns> </returns> Public static string reverseusingxor (string Str) {char [] arr = Str. tochararray (); int L = Str. length-1; // exchange value for (INT I = 0; I <L; I ++, l --) {arr [I] ^ = arr [l]; arr [l] ^ = arr [I]; arr [I] ^ = arr [l];} return new string (ARR );}
So far, we have finished three methods of string reversal. Maybe there is still a better way for the visitor. Please leave your comments in your comments. :-)
For movies and TV series, the most exciting part is usually the second half. Therefore, Xiaosheng'sArticleAnd move the most important part to the back. I designed a test method to test the performance of the above three string reversal methods. The method is as follows:
Public Delegate string funcdelegate (string S ); /// <summary> /// test method /// </Summary> /// <Param name = "Description"> method description </param> /// <Param name = "func"> test method </param> /// <Param name = "times"> Number of executions </param> /// <Param name = "str"> test string </param> Public static void benchmark (string description, funcdelegate func, int times, string Str) {stopwatch Sw = new stopwatch (); Sw. start (); For (Int J = 0; j <times; j ++) {func (STR);} SW. stop (); console. writeline ("method {0}: Call {1} Times, in use {2 }. ", description, times, SW. elapsedticks );}
There is also a method to generate random strings, please refer to the Code:
/// <Summary> /// generate a random string of the specified length /// </Summary> /// <Param name = "length"> length of the string </param>/ // <returns> </returns> Public static string randomstring (INT length) {random = new random (); stringbuilder sb = new stringbuilder (); For (INT I = 0; I <length; I ++) {sb. append (convert. tochar (convert. toint32 (math. floor (26 * random. nextdouble () + 65);} return sb. tostring ();}
Next, the main character debuted. See the main entry method:
Static void main (string [] ARGs) {int [] lengths = new int [] {1, 10, 15, 25, 50, 75,100,100 0, 100000 }; foreach (INT Len in lengths) {// each method is executed 10000 times, and the precision int iterations = 10000; // generate a random test string teststring = stringreverse. randomstring (LEN); // print the test information stringreverse. benchmark (string. format ("string Builder (test string length: {0})", Len), stringreverse. reverseusingstringbuilder, iterations, teststring); stringreverse. benchmark (string. format ("array. reverse (test string length: {0}) ", Len), stringreverse. reverseusingchararray, iterations, teststring); stringreverse. benchmark (string. format ("XOR (test string length: {0})", Len), stringreverse. reverseusingxor, iterations, teststring); console. writeline ();} console. read ();}
View the result after running. The result is as follows:
Conclusion:From the running results, we can see that,
Exclusive orAs the length of the string increases, the implementation of the reverse method will take longer and longer. However, when the length of a string is small, it is the best among the three methods.
StringbuilderThe string reversal is the worst performance regardless of the length of the string. I personally estimate the performance loss caused by opening up new memory overhead.
Array. ReverseThe most stupid method to implement string reversal is the most stable performance among the above three methods. Medium reason, which should be evaluated by the audience.
Finally, attach the C # string reversal on stackoverflow.AlgorithmA discussion post address
Http://stackoverflow.com/questions/228038/best-way-to-reverse-a-string-in-c-sharp-2-0