Reversing a string is a popular question in most campus hiring interviews. There could be several ways one can think of to do this. We will be looking at some of those.
In this article we will not look at the Reverse method provided by the .NET libraries; we will instead try to implement it by our own logic. However we will be using the ToCharArray method in most of our examples.
Let’s start with the most basic that uses two arrays, one to store the input and another for the output and uses two variables to traverse from the begining and end and assigns the values from the input array to the output array.
- ///Need one extra array for result, need to traverse full array.
- public static stringReverseString1(string str) {
- char[] chars = str.ToCharArray();
- char[] result = newchar[chars.Length];
- for (int i = 0, j = str.Length - 1; i < str.Length; i++, j--) {
- result[i] = chars[j];
- }
- return new string(result);
- }
I am sure we can do much better here, so let’s do that. Now we will use the swapping for the same (as we used in the sorting algorithms) also if you look at, we are only traversing half of the array.
- ///Uses swap method to reverse; need to traverse only half of the array.
- public static stringReverseString2(string str) {
- char[] chars = str.ToCharArray();
- for (int i = 0, j = str.Length - 1; i < j; i++, j--) {
- char c = chars[i];
- chars[i] = chars[j];
- chars[j] = c;
- }
- return new string(chars);
- }
Don’t want to use any temp variable, so this is for you, here we are using an in-pace swap.
- ///Here is the use of in-place swap without any temp variable
- public static stringReverseString3(string str) {
- char[] chars = str.ToCharArray();
- for (int i = 0, j = str.Length - 1; i < j; i++, j--) {
- chars[i] = str[j];
- chars[j] = str[i];
- }
- return new string(chars);
- }
Following is similar to above except its without copy to char array.
- ///String Reversal without Copy to Char Array it's i <= j as we need to getthe middle /// character in case of odd number of characters in the string
- public static stringReverseString3b(string str) {
- char[] chars = new char[str.Length];
- for (int i = 0, j = str.Length - 1; i <= j; i++, j--) {
- chars[i] = str[j];
- chars[j] = str[i];
- }
- return new string(chars);
- }
Now let’s try something new, Stacks, we all know how stack works, in other words LIFO. So we will be using the same here.
- ///String reversal with stack [Please note here Stack_Array is my custom Stackclass, ///you can replace this with provided by .NET]
- public static stringReverseString4(string str) {
- Stack_Array stk1 = newStack_Array(str.Length);
- foreach(charc in str)
- stk1.Push(c);
- string revString = null;
- foreach(charc in str)
- revString += stk1.Pop();
- return revString;
- }
Now for something very different, XOR; yes we will be using XOR to reverse the string. Want to know how it works? First try it out on pen and paper. I have also explained it in the comments however it’s better if you try it yourself first.
- ///String reversal with XOR (^); interesting way to reversal
- /// A[i] = A[i] ^ A[len] -> A[i] = 80 ^ 73 -> A[i] = 25
- /// A[len] = A[len] ^ A[i] -> A[len] = 73 ^ 25 -> A[len] = 80
- /// A[i] = A[i] ^ A[len] -> A[i] = 25 ^ 80 -> A[i] = 73
- public static stringReverseString5(string str) {
- char[] inputstream = str.ToCharArray();
- int length = str.Length - 1;
- for (int i = 0; i < length; i++, length--) {
- inputstream[i] ^= inputstream[length];
- inputstream[length] ^= inputstream[i];
- inputstream[i] ^= inputstream[length];
- }
- return new string(inputstream);
- }
So much for iterative ways. Now to try recursion. The following is probability the shortest and simplest way to reverse a sting using recursion.
- ///Recursion method; simple and regular performance for small strings
- public static stringReverseString_Rec(string str) {
- if (str.Length <= 1) return str;
- else return ReverseString_Rec(str.Substring(1)) + str[0];
- }
Another variant using recursion is not so short but is simple though.
- ///Another way of recursion; need to index as 0
- public static stringReverseString_Rec2(string str, int index) {
- char[] chars = str.ToCharArray();
- int len = chars.Length;
- if (index < len / 2) {
- char c = chars[index];
- chars[index] = chars[len - index - 1];
- chars[len - index - 1] = c;
- index++;
- return ReverseString_Rec2(new string(chars), index);
- } else {
- return new string(chars);
- }
- }
Please let me know your comments/suggestions or if you have a better way.


Alex ArzamascevPosted May 9, 2020, 5:08 AM EDT
Another possible algorithm public static string Reverse(this string str) { string reversedWord = ""; for (int wordNumber = str.Length; wordNumber > 0; wordNumber--) { reversedWord += str[wordNumber - 1]; } return reversedWord; }
Mahenderker Praveen KumarPosted May 31, 2019, 10:30 PM EDT
I have been asked to Reverse a string without inbuilt functions and I presented this way public void ReverseInputString() { Console.WriteLine("Enter a String to reverse:"); var inputstr = Console.ReadLine().Trim(); var outPutstr = string.Empty; foreach (var item in inputstr.ToCharArray()) { outPutstr = item + outPutstr; } Console.WriteLine("Reverse of '" + inputstr + "': " + outPutstr); }
Amol KumbhkarnaPosted May 8, 2018, 11:41 PM EDT
Great article ...!!! Keep It Up....!!!
ajay dagadePosted Dec 29, 2017, 12:09 AM EST
Class Program { static void Main(string[] args) { Console.WriteLine("Enter Any String:"); string a = Console.ReadLine(); Console.WriteLine(" String IS:{0}",a); string b = ""; int l = (a.Length-1);// for (int i = -5; i <=l; i++) { b = b + a[l]; l--; } Console.WriteLine(" String IS:{0}", b); Console.ReadKey(); } }
Hemant GaurPosted May 5, 2017, 6:47 AM EDT
Recursive method will throw StackOverFlow Exception
Umesh ApPosted Feb 16, 2017, 7:53 PM EST
Prakash Tripathi, Very very nice explaination. I can point out another method with only 2 lines of code. string str = "ABCD"; str = new String(str.Reverse().ToArray()); Console.WriteLine(str);
Prakash TripathiTOP 100Posted Jan 2, 2017, 6:52 AM EST
@Sheikh Zubayr, you are right. Stacks are LIFO, FIFO is added by mistake, I will make a correction. Thnx for pointing it.
Prakash TripathiTOP 100Posted Jan 2, 2017, 6:50 AM EST
@Mohamed Amine Zghal. Agree with you.
Prakash TripathiTOP 100Posted Jan 2, 2017, 6:49 AM EST
@Ramakrishna, char[] chars = str.ToCharArray(); will not just declare the char array but also stores the characters of str in it. However char[] chars = new char[str.Length]; will only declare the array of a given length. Hope that clarifies.
Sheikh ZubayrPosted Dec 29, 2016, 12:49 AM EST
One mistake that I see here is, you have mentioned Stacks as FIFO. All my life I knew Stacks are LIFO i.e. Last In First Out. FIFO is for queues. Correct me if i am wrong
Mohamed Amine ZghalPosted Dec 7, 2016, 10:09 AM EST
Public function ReverseString3(string str){ char[] arr = str.ToCharArray();Array.Reverse(arr); return new string(arr); } this is the simplest way ;)
RamakrishnaPosted Jul 21, 2016, 9:24 PM EDT
Good stuff but the char[] chars = str.ToCharArray(); in swap examples is unnecessary. We can simply declare the array to have big enough size to hold the reversed string. Something like char[] chars = new char[str.Length];
Prakash TripathiTOP 100Posted May 6, 2016, 4:53 AM EDT
Thnx Raja.
Raja TPosted May 6, 2016, 4:34 AM EDT
Nice, Thanks for sharing..Great job..
Prakash TripathiTOP 100Posted Mar 6, 2016, 5:18 PM EST
Thnx Kumaresh. However I love to hear more detailed comments from you.
Prakash TripathiTOP 100Posted Mar 6, 2016, 5:17 PM EST
Thnx Karthiga, However I didn't understand the purpose of duplicate posts.
Prakash TripathiTOP 100Posted Mar 6, 2016, 5:15 PM EST
@Josh. We could use the .Net API as you pointed out. However the idea of the article was to present implementations of such API's and invoke the thought process around.
Prakash TripathiTOP 100Posted Mar 6, 2016, 5:12 PM EST
Agree Jaydip..That could be another way to achieve this.
Prakash TripathiTOP 100Posted Mar 6, 2016, 4:55 PM EST
Thnx Madhu.
Kumaresh RajalingamPosted Mar 6, 2016, 3:25 PM EST
good one
Kumaresh RajalingamPosted Mar 6, 2016, 3:25 PM EST
Nice explanation
Sr KarthigaPosted Mar 6, 2016, 3:23 PM EST
Nice explanation
Sr KarthigaPosted Mar 6, 2016, 3:12 PM EST
good one
Sr KarthigaPosted Mar 6, 2016, 3:12 PM EST
Nice explanation
Prakash TripathiTOP 100Posted Feb 25, 2016, 2:27 AM EST
Thnx Sonu.
Sonu ChaudharyPosted Feb 25, 2016, 2:16 AM EST
nice article
Prakash TripathiTOP 100Posted Dec 29, 2015, 12:35 AM EST
Thnx Dhanik
Dhanik SahniPosted Dec 28, 2015, 9:41 PM EST
Nice
Josh DeLongPosted Aug 4, 2015, 6:07 AM EDT
char[] textArray = text.ToCharArray();Array.Reverse(textArray); return new string(textArray); This is the fastest way I've found to reverse a string in C#. It uses the native array reverse method.
Jaydip JadhavPosted May 14, 2015, 11:08 PM EDT
String str1="Reversing";String str2; foreach(char c in str1){ str2=c+' '+str2; } //str2 reverse string //Happy Coding :)
madhu sudhanPosted Dec 17, 2014, 6:47 AM EST
Nice work buddy
Prakash TripathiTOP 100Posted Feb 2, 2014, 7:54 AM EST
This is simple, however lacks optimization as full array is traversed also sting concatenation is expensive for large strings.
Rajiv NadendlaPosted Jan 30, 2014, 7:37 AM EST
I have an easy way you may know it.. public static string ReverseOfString(string str) { string reverseStr = string.Empty; for (int i = str.Length-1; i >=0; i--) { reverseStr = reverseStr str[i]; } return reverseStr; }
Rajiv NadendlaPosted Jan 30, 2014, 7:37 AM EST
I have an easy way you may know it.. public static string ReverseOfString(string str) { string reverseStr = string.Empty; for (int i = str.Length-1; i >=0; i--) { reverseStr = reverseStr str[i]; } return reverseStr; }