Bhavya

Code -> Break -> Fix -> Blog

Ways to reverse a string in C#

Leave a comment

1. Normal Reverse

public static string ReverseNormal(string source)
 {
 int length = source.Length;
 char[] sourceArr = source.ToCharArray();
 char[] destinationArr = new char[length];
 for (int i = 0; i < length; i++)
 {
 destinationArr[length - 1 - i] = sourceArr[i];
 }

return new string(destinationArr);
 }

2. Using Array.Reverse()

public static string ReverseArrayReverse(string source)
 {
 return new string(source.ToCharArray().Reverse().ToArray());
 }

3. Swapping

public static string ReverseSwap(string source)
 {
 char[] sourceArr = source.ToCharArray();
 for (int i = 0, j = source.Length - 1; i <= j; i++, j--)
 {
 var temp = sourceArr[i];
 sourceArr[i] = sourceArr[j];
 sourceArr[j] = temp;
 }

 return new string(sourceArr);
 }

4. Swapping without temp variable

public static string ReverseSwapWithoutTemp(string source)
 {
 char[] sourceArr = source.ToCharArray();
 for (int i = 0, j = source.Length - 1; i <= j; i++, j--)
 {
 sourceArr[i] = source[j];
 sourceArr[j] = source[i];
 }

 return new string(sourceArr);
 }

5. Using Stack

public static string ReverseStack(string source)
 {
 Stack<char> reverseStack = new Stack<char>();

 foreach (var ch in source)
 {
 reverseStack.Push(ch);
 }

 string output = null;
 foreach (var ch in reverseStack)
 {
 output += ch;
 }

 return output;
 }

6. Recursive (Option 1)

public static string ReverseRecursive(string source)
 {
 if (source.Length <= 1)
 {
 return source;
 }

 return ReverseRecursive(source.Substring(1)) + source[0];
 }

7. Recursive (Option 2)

public static string ReverseRecursiveIndex(int index, string source)
 {
 var lenght = source.Length;
 char[] sourceArr = source.ToCharArray();

 if (index < lenght / 2)
 {
 sourceArr[index] = source[lenght - 1 - index];
 sourceArr[lenght - index - 1] = source[index];
 index++;
 return ReverseRecursiveIndex(index, new string(sourceArr));
 }

 return new string(sourceArr);
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s