Simple reversal
Naïve solution, reverse traversal, string concatenation, string performance is low, in length known premise can use char array instead
public static string Naivereverse (string text) { string reverse = string. Empty; for (int i = text. Length-1; I >= 0; i--) { reverse + = text[i] ; } return reverse;}
StringBuilder stitching
Further improvements, using StringBuilder for stitching strings
public static string Sbreverse (string text) { StringBuilder builder = new StringBuilder (text. Length); for (int i = text. Length-1; I >= 0; i--) { Builder. Append (Text[i]); } Return builder. ToString ();}
Two-point reversal
How does the traversal count fall to half?
public static string Binaryreverse (string text) { char[] Chararray = text. ToCharArray (); int len = text. Length-1; for (int i = 0; i < len; i++, len--) { char tmp = chararray[i]; Chararray[i] = Chararray[len]; Chararray[len] = tmp; } return new string (Chararray);}
Pointer manipulation
Hey? String actually variable?
public static unsafe string Unsafereverse (string text) { fixed (char* ptext = text) { char* Pstart = ptext;
char* pEnd = ptext + text. Length-1; for (int i = text. LENGTH/2; I >= 0; i--) { char temp = *pstart; *pstart++ = *pend; *pend--= temp; } return text; }}
Array inversion
The easiest way to understand is often the most efficient and why is it so efficient?
public static string Arrayreverse (string text) { char[] Chararray = text. ToCharArray (); Array.reverse (Chararray); return new string (Chararray);}
XOR operation
Does it have a lot of force? In fact, for the understanding bit operation is still a bit of help, as for performance ...
public static string Xorreverse (string text) { char[] Chararray = text. ToCharArray (); int len = text. Length-1; for (int i = 0; i < len; i++, len--) { chararray[i] ^= Chararray[len]; Chararray[len] ^= chararray[i]; Chararray[i] ^= Chararray[len]; } return new string (Chararray);}
FCL Implementation
Upgrade to. NET3.5, huh? OK, the least code implementation, but performance, the amount
public static string Enumreverse (string text) { char[] reverse = text. Reverse (). ToArray (); return new string (reverse);}
Test
Stopwatch watcher = new Stopwatch ();//String size int[] sizes = new[] {10, 100, 1000, 10000};//reversal method list var reversemethods = new Func<string, string>[]{ naivereverse, sbreverse, binaryreverse, unsafereverse , Arrayreverse, xorreverse, enumreverse};for (int i = 0; i < sizes. Length; i++) { string text = new String (' X ', sizes[i]); Console.WriteLine ("for Size: {0}", Sizes[i]); for (int j = 0; J < Reversemethods.length; J + +) { var invoker = reversemethods[j]; Watcher. Restart (); Invoker (text); Watcher. Stop (); Console.WriteLine ("{0} Ticks: {1}", Invoker. Method.name, watcher. elapsedticks); } Console.WriteLine ();} Console.ReadLine ();
Conclusion
What is the point of writing this code? What about performance? Okay, so here's the problem.
C # Programming Practice--string inversion