Created
June 28, 2016 19:42
-
-
Save jianminchen/9ad0fff7c0e1d3f7294ef3dcc24b933d to your computer and use it in GitHub Desktop.
string reverse - C# - various ways
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace stringArray | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string test = "abcd"; | |
string result = Reverse_6(test); | |
} | |
public static string Reverse(string s) | |
{ | |
char[] charArray = s.ToCharArray(); | |
Array.Reverse(charArray); | |
return new string(charArray); | |
} | |
/* | |
* Enumerable.Reverse | |
* string.Concat | |
* | |
* | |
*/ | |
public static string stringReverse_2(string s) | |
{ | |
return string.Concat(Enumerable.Reverse(s)); | |
} | |
public static string stringReverse_3(string s) | |
{ | |
return new string(s.Reverse().ToArray()); | |
} | |
/* | |
* string construct - IEnumberable | |
* string.ToCharArray() | |
* IEnumerable.Reverse() | |
* IEnumerable.ToArray() | |
* | |
*/ | |
public static string stringReverse_4(string s) | |
{ | |
return new string(s.ToCharArray().Reverse().ToArray()); | |
} | |
/* | |
Firstly you don't need to call ToCharArray as a string can | |
already be indexed as a char array, so this will save you an allocation. | |
The next optimisation is to use a StringBuilder to prevent | |
unnecessary allocations (as strings are immutable, concatenating them | |
makes a copy of the string each time). To further optimise this we | |
pre-set the length of the StringBuilder so it won't need to expand | |
its buffer. | |
* | |
* string.isNullOrEmtpy | |
* string.Empty | |
* | |
*/ | |
public string Reverse_5(string text) | |
{ | |
if (string.IsNullOrEmpty(text)) | |
{ | |
return text; | |
} | |
StringBuilder builder = new StringBuilder(text.Length); | |
for (int i = text.Length - 1; i >= 0; i--) | |
{ | |
builder.Append(text[i]); | |
} | |
return builder.ToString(); | |
} | |
public static string Reverse_6(string text) | |
{ | |
return text.Reverse(); | |
} | |
} | |
// Of course you can extend string class with Reverse method | |
public static class StringExtensions | |
{ | |
public static string Reverse(this string input) | |
{ | |
return string.Concat(Enumerable.Reverse(input)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment