Updated on
To reverse a string in C#, we copy its characters into a char[] with ToCharArray(), reverse the array with Array.Reverse(), and create a new string from it. Strings are immutable, so every technique returns the reversed string and leaves the input alone.
That works for plain text. Emoji stored as two char values and accents written as two code points need reversing by text elements, which we also cover. At the end, we benchmark all nine methods on .NET 11 to help you choose the best approach for your use case.
Let’s start!
Application Setup
To explore ways to reverse a string in C#, let’s start by creating a console application using the Visual Studio Project wizard or the dotnet new console command.
For each solution, we will add a public static method to a Methods class in the StringReverse namespace. Each method takes a string as an argument and returns one, too.
Strings in C# are immutable, so none of these techniques changes the input string. Some of them build the result piece by piece in a new data structure, while others reverse a char array or a span in place and then turn it into the new string. The choice of technique may depend on the size of the string, the performance requirements, and the available memory. We explore different approaches in C#, discuss their tradeoffs, and compare their performance.
We’ll start by setting up a simple example to test against our methods:
var input = "abcdefg";
We construct a simple string using the first seven letters of the Latin alphabet and we expect to return the letters in reversed order: "gfedcba".
Use Array.Reverse() Method to Reverse a String
The first method to reverse a string we’ll look at is the Reverse() method from the Array class:
public static string ArrayReverseString(string stringToReverse)
{
var charArray = stringToReverse.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
First, we convert the input string into a character array using the ToCharArray() method provided by the string class in C#. This method splits a string into its constituent characters and stores them in a char[].
Next, we use the Reverse() method to reverse the order of the elements in the charArray collection.
Finally, we convert the reversed charArray back into a string using the string constructor that takes an array of characters as input, and we return it.
The result is the following:
ArrayReverseString: gfedcba
As we expect, the result is the initial string’s characters in reverse order.
Enumerable Reverse() Extension Method for String Reversion
Our next solution uses the Reverse() extension method of the Enumerable class:
public static string EnumerableReverseMethod(string stringToReverse)
{
return string.Concat(Enumerable.Reverse(stringToReverse));
}
The Enumerable.Reverse() method takes a collection (in this case, a string) and returns an IEnumerable<char>. Here, it represents a sequence of characters in reverse order.
To convert the reversed sequence of characters back into a string, we use the string.Concat() method, which concatenates a sequence of characters into a single string.
In this case, we pass the reversed sequence to create a new string with the characters in reverse order.
Reverse a String With Recursion
Another option for reversing a string is to use recursion:
public static string RecursiveStringReverseMethod(string stringToReverse)
{
if (stringToReverse.Length <= 1)
return stringToReverse;
return stringToReverse[^1] + RecursiveStringReverseMethod(stringToReverse[1..^1]) + stringToReverse[0];
}
Initially, we check if the length of the input string is less than or equal to 1. If this is the case, we simply return the input string.
Otherwise, we call the RecursiveStringReverseMethod() method recursively, passing in the substring of the input string each time, excluding the first and last characters using the stringToReverse[1..^1] object. We return the concatenation of the last character of the input string (stringToReverse[^1]), the result of the recursive call, and the first character of the input string (stringToReverse[0]).
In C# 8.0, two new concepts were introduced, Ranges and Indices. In [^1], the ^ is the index from end operator, so the index counts from the end of the string. In other words, stringToReverse[^1] is equivalent to stringToReverse[stringToReverse.Length - 1], which accesses the last character of the string.
The [1..^1] syntax specifies a range that starts at the second character and ends at the second-to-last character. The end of a range is exclusive, and ^1 means one index from the end of the string.
This effectively reverses the input string using recursion.
Reverse a String Using a Loop and XOR Operator
Now we will utilize the XOR operator within iterations to reverse our string:
public static string ReverseXorMethod(string stringToReverse)
{
var charArray = stringToReverse.ToCharArray();
var len = stringToReverse.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);
}
First, we convert the string into a char[] and initialize an integer variable len to the length of the input string minus one.
We use a loop to swap the characters at the beginning and end of the charArray, iterating from the start of the array to the middle. In each iteration of the loop, we perform three steps using XOR swapping to swap the characters at i and len index. The ^= operator is the XOR assignment operator. It performs the XOR operation on the two operands and assigns the result to the left operand.
Once the loop completes the iterations, the charArray contains the reversed string. Finally, we return a new string from the reversed charArray.
Use Stack to Reverse a String
Next, we can use the Stack class, which is a last-in, first-out (LIFO) stack of objects, to reverse a string:
using System.Text;
public static string StackReverseMethod(string stringToReverse)
{
var resultStack = new Stack<char>();
foreach (char c in stringToReverse)
{
resultStack.Push(c);
}
var sb = new StringBuilder();
while (resultStack.Count > 0)
{
sb.Append(resultStack.Pop());
}
return sb.ToString();
}
Here, we iterate the input string stringToReverse character by character using a foreach loop, and we push each character onto a resultStack stack. This means that the characters come off the stack in reverse order, effectively reversing the string.
We create a new StringBuilder object to construct the reversed string by popping characters from the stack and appending them to the StringBuilder. The while loop continues to pop characters from the stack and append them to the StringBuilder until there are no more characters left in the stack.
Finally, we return the reversed string by calling the ToString() method on the StringBuilder object.
How Do We Reverse a String With StringBuilder?
StringBuilder has no Reverse() method, so there is nothing to call on it directly. We have to do the reversing ourselves: read the input string from its last character to its first and append each one to the builder.
This is a good fit when we are already assembling text in a StringBuilder, for example when the reversed part is one piece of a longer string we build in a loop. Appending the characters in reverse order saves us a separate reversal step.
If all we need is the reversed string, Array.Reverse() on a char[] does the same job in less code. It is faster too: in our benchmark, it reversed a 64-character string about four and a half times faster than the StringBuilder loop.
Like every method so far, this one works one char at a time. That is fine for plain text, but it breaks emoji and other characters stored as two char values, as we’ll see shortly.
Here’s the method:
public static string StringBuilderReverseMethod(string stringToReverse)
{
var sb = new StringBuilder(stringToReverse.Length);
for (int i = stringToReverse.Length - 1; i >= 0; i--)
{
sb.Append(stringToReverse[i]);
}
return sb.ToString();
}
First, we create a new StringBuilder object with an initial capacity equal to the length of the input string stringToReverse. With this, we ensure that the StringBuilder has enough space to hold the entire reversed string without needing to resize the buffer.
Next, we iterate over the characters in the input string in reverse order using a for loop. In each iteration of the loop, the method appends the current character using the Append() method. This effectively adds the characters to the StringBuilder in reverse order, so that the final result is the desired one.
Finally, we return the string by calling the ToString() method on the StringBuilder object.
Use Create() Method to Create a String in Reverse Order
The static string.Create() method can be used for the same purpose:
public static string StringCreateMethod(string stringToReverse)
{
return string.Create(stringToReverse.Length, stringToReverse, (chars, state) =>
{
state.AsSpan().CopyTo(chars);
chars.Reverse();
});
}
Here, we use the string.Create() method to create a new string that is a reversed version of the input string stringToReverse. The string.Create() method takes a length, a state object, and a callback function as parameters. It creates a new string of specified length and passes it to the callback function, along with the state object. The callback function fills in the characters of the new string. It doesn’t return anything.
In this method, the state object is the input stringToReverse string, which is passed to the string.Create() method as the second argument. We define the callback function as an anonymous method that takes two parameters: chars and state. The chars object is a span of characters that represents the newly created string, and the state is the original input string.
The first line of the callback function copies the characters of the input string to the new string using the CopyTo() method of the ReadOnlySpan<char> struct. This initializes the new string to be the same as the input string.
The second line of the callback function reverses the characters of the chars span in place, using the Reverse() extension method that MemoryExtensions provides for spans. This effectively reverses the order of the characters in the new string, giving us our final reversed string.
LINQ Reverse() Extension Method
The last char-based solution we’ll look at calls Reverse() directly on the string. The string class has no Reverse() method of its own. Since string implements IEnumerable<char>, the call binds to the same Enumerable.Reverse() method we used earlier, this time as an extension method:
public static string StringExtensionReverseMethod(string stringToReverse)
{
return new string(stringToReverse.Reverse().ToArray());
}
Here, we use the LINQ Reverse() extension method and the ToArray() method to create a new string that is a reversed version of the input string stringToReverse.
We use the string constructor to create a new string from the reversed character array and we return it.
How Do We Reverse a String With Emoji or Accents in C#?
A char in C# is one UTF-16 code unit, which is not always one visible character. Most emoji, musical symbols and other characters outside the Basic Multilingual Plane take two char values, called a surrogate pair. An accented letter can also be two code points: the letter, then a combining mark.
Every method we’ve seen so far reverses the string one char at a time. On a surrogate pair, that swaps the two halves into an order that means nothing. On a combining mark, the mark ends up on the wrong letter.
What we need to reverse instead are text elements, the .NET name for what a reader sees as one character. StringInfo.GetTextElementEnumerator() walks a string one text element at a time. We copy each element, whole and in its original order, to the mirrored position in the new string.
It is also the slowest method on short strings, so we save it for text that can contain such characters.
Microsoft Learn’s introduction to character encoding in .NET says that “surrogate code points are meaningful only as pairs.”
For example, each character of a music notes collection (e.g. 𝅗𝅥𝄞𝅘𝅥𝅮𝅘𝅥𝅯) is a surrogate pair. We use the following approach to reverse it:
using System.Globalization;
public static string TextElementEnumeratorMethod(string stringToReverse)
{
return string.Create(stringToReverse.Length, stringToReverse, (chars, val) =>
{
var valSpan = val.AsSpan();
var en = StringInfo.GetTextElementEnumerator(val);
en.MoveNext();
var start = en.ElementIndex;
var pos = chars.Length;
while (en.MoveNext())
{
var next = en.ElementIndex;
var len = next - start;
valSpan[start..next].CopyTo(chars[(pos - len)..pos]);
pos -= len;
start = next;
}
valSpan[start..].CopyTo(chars[0..pos]);
});
}
We use the string.Create() method to efficiently create a new string with a specified length and content. The chars parameter of the Create() callback is a span of characters to write to. The val parameter is the value of the input string.
We create a TextElementEnumerator object using the StringInfo.GetTextElementEnumerator() method, passing in the val parameter. This object allows us to enumerate over the text elements of val. We also take a span over val, so we can copy each text element as a slice without allocating a substring for it.
Then, we iterate over the text elements from first to last, and copy each one into the new string starting from the end.
First, we get the index of the current text element using the ElementIndex property of the TextElementEnumerator, and we calculate the length of the previous text element by subtracting its index.
Next, we use the CopyTo() method to copy the text element to the appropriate position in the new string, which is given by the chars span. To calculate its position, we use the pos variable, which starts at the end of the new string and is decremented by the length of each text element.
Finally, the loop always stops one element short, because each step copies the element that came before. So we copy the last text element to the beginning of the new string. This step also covers a string that holds a single text element.
Let’s see the difference on our music notes, and on a title where the é is written as an e followed by a combining acute accent:
using System.Text;
using static StringReverse.Methods;
Console.OutputEncoding = Encoding.UTF8;
var musicNotes = "\U0001D15E\U0001D11E\U0001D160\U0001D161";
var accented = "Les Mise\u0301rables";
foreach (var text in new[] { musicNotes, accented })
{
Console.WriteLine();
Console.WriteLine($"Input: {text} (Length: {text.Length})");
Console.WriteLine(nameof(ArrayReverseString) + ": " + ArrayReverseString(text));
Console.WriteLine(nameof(TextElementEnumeratorMethod) + ": " + TextElementEnumeratorMethod(text));
}
We write both strings with escape sequences, so we can see exactly which code points they hold. Four notes take eight char values:
Input: 𝅗𝅥𝄞𝅘𝅥𝅮𝅘𝅥𝅯 (Length: 8) ArrayReverseString: �𝅘𝅥𝅮𝄞𝅗𝅥� TextElementEnumeratorMethod: 𝅘𝅥𝅯𝅘𝅥𝅮𝄞𝅗𝅥 Input: Les Misérables (Length: 15) ArrayReverseString: selbaŕesiM seL TextElementEnumeratorMethod: selbarésiM seL
Array.Reverse() puts each low surrogate in front of its high surrogate. All four notes share the same high surrogate, so three pairs happen to form again, but the first and last char have no partner and show up as replacement characters (�). In the second example, the accent has moved from the e to the r. TextElementEnumeratorMethod() gets both strings right.
What’s the Fastest Way to Reverse a String in C#?
string.Create() and Array.Reverse() on a char[] are the two fastest ways we measured, in that order. In our benchmark run on .NET 11, string.Create() reversed a 64-character string in about 20 nanoseconds and Array.Reverse() in about 34 nanoseconds.
They also differ in memory. string.Create() writes the reversed characters straight into the new string, so it allocates only the result. Array.Reverse() first needs a char[] copy of the input, so it allocates twice as much.
The XOR swap, StringBuilder and LINQ come next. Stack<char> and recursion trail behind, and recursion gets much worse as the string grows, because every call builds new strings.
TextElementEnumerator is the slowest of all on short strings, but it’s the only method here that keeps emoji and accents intact. If our text can contain them, it’s the one to use.
Let’s evaluate these methods to find the most efficient one with the benchmark class. We run every method on a random string of 64 characters and on one of 1,024 characters. First, let’s create a method to generate a random string of a given length:
public static string GenerateText(int length)
{
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
var builder = new StringBuilder(length);
for (int i = 0; i < length; ++i)
{
var index = random.Next(alphabet.Length);
builder.Append(alphabet[index]);
}
return builder.ToString();
}
Here, we generate a random string of characters by selecting characters from a pre-defined set. The set includes upper and lower case letters of the English alphabet and numeric digits.
The benchmark class lives in a separate console project that references the BenchmarkDotNet package and our StringReverse project. The class also holds GenerateText(), creates the input once per method and length and returns the reversed string from every benchmark method:
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
using StringReverse;
namespace BenchmarkRunner;
[InProcess]
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
public class StringReverseBenchmark
{
private string _randomString = string.Empty;
[Params(64, 1024)]
public int Length { get; set; }
[GlobalSetup]
public void Setup() => _randomString = GenerateText(Length);
[Benchmark]
public string UsingArrayReverseString() => Methods.ArrayReverseString(_randomString);
// one [Benchmark] method for each of the other eight methods
}
Returning the result keeps the JIT compiler from skipping the work, and [MemoryDiagnoser] adds the Allocated column.
The benchmark project’s Program.cs hands the class to BenchmarkDotNet:
using BenchmarkDotNet.Running; using BenchmarkRunner; BenchmarkSwitcher.FromAssembly(typeof(StringReverseBenchmark).Assembly).Run(args);
Now we’re ready to run it in the Release configuration with dotnet run -c Release -- --filter "*" and analyze our benchmark results:
| Method | Length | Mean | Error | StdDev | Rank | Allocated | |---------------------------------------- |------- |-------------:|-------------:|-------------:|-----:|----------:| | UsingStringCreateMethod | 64 | 20.46 ns | 0.342 ns | 0.303 ns | 1 | 152 B | | UsingArrayReverseString | 64 | 34.40 ns | 0.793 ns | 2.288 ns | 2 | 304 B | | UsingReverseXorMethod | 64 | 84.59 ns | 1.661 ns | 1.473 ns | 3 | 304 B | | UsingStringBuilderReverseMethod | 64 | 157.12 ns | 1.771 ns | 1.657 ns | 4 | 352 B | | UsingStringExtensionReverseMethod | 64 | 160.18 ns | 2.112 ns | 1.976 ns | 4 | 352 B | | UsingStringCreateMethod | 1024 | 160.74 ns | 3.205 ns | 5.941 ns | 4 | 2072 B | | UsingArrayReverseString | 1024 | 254.41 ns | 6.511 ns | 19.096 ns | 5 | 4144 B | | UsingEnumerableReverseMethod | 64 | 354.45 ns | 2.455 ns | 2.296 ns | 6 | 352 B | | UsingStackReverseMethod | 64 | 410.66 ns | 3.948 ns | 3.693 ns | 7 | 896 B | | UsingRecursiveStringReverseMethod | 64 | 758.29 ns | 11.332 ns | 16.961 ns | 8 | 5736 B | | UsingReverseXorMethod | 1024 | 1,170.47 ns | 23.267 ns | 32.617 ns | 9 | 4144 B | | UsingStringExtensionReverseMethod | 1024 | 1,240.55 ns | 24.465 ns | 25.123 ns | 10 | 4192 B | | UsingStringBuilderReverseMethod | 1024 | 1,563.39 ns | 29.275 ns | 28.752 ns | 11 | 4192 B | | UsingTextElementEnumeratorReverseMethod | 64 | 1,761.20 ns | 18.601 ns | 15.533 ns | 12 | 152 B | | UsingEnumerableReverseMethod | 1024 | 4,290.97 ns | 18.971 ns | 15.842 ns | 13 | 4192 B | | UsingStackReverseMethod | 1024 | 6,514.52 ns | 59.317 ns | 55.485 ns | 14 | 8960 B | | UsingTextElementEnumeratorReverseMethod | 1024 | 27,812.21 ns | 201.779 ns | 188.744 ns | 15 | 2072 B | | UsingRecursiveStringReverseMethod | 1024 | 96,086.20 ns | 1,889.872 ns | 2,522.925 ns | 16 | 1075176 B |
We can see that StringCreateMethod() and ArrayReverseString() are the most efficient in terms of speed, at both lengths.
StringCreateMethod() is fast because it skips the intermediate copy. string.Create() allocates the new string once and hands its characters to our callback as a Span<char>, so we copy and reverse directly inside the result. The Allocated column shows exactly one string per call.
ArrayReverseString() comes second. Array.Reverse() reverses the character array in place, but ToCharArray() has already allocated that array, so this method allocates twice as much memory as StringCreateMethod().
In contrast, the RecursiveStringReverseMethod() method has poor results, as each recursive call to the method involves multiple string concatenations to build the final reversed string. With 1,024 characters, a single call allocated about 1 MB.
Regarding the TextElementEnumeratorMethod() method, the result depends on the length. With 64 characters it is the slowest method of all, but with 1,024 characters it beats the recursive one by a wide margin. It’s worth mentioning, though, that TextElementEnumeratorMethod() is the only method here that reverses strings with surrogate pairs and combining characters correctly.
Here are all nine methods side by side, with what they allocate and whether they handle emoji and accents:
| Method | How it reverses | Allocated, 64 chars | Emoji and accents |
|---|---|---|---|
string.Create() | Copies into the new string and reverses the span | 152 B | Broken |
Array.Reverse() | Reverses a char[] copy in place | 304 B | Broken |
| XOR loop | Swaps char values in a char[] copy | 304 B | Broken |
StringBuilder loop | Appends from the last char to the first | 352 B | Broken |
LINQ Reverse().ToArray() | Enumerable.Reverse() into a new array | 352 B | Broken |
Enumerable.Reverse() with string.Concat() | Concatenates the reversed sequence | 352 B | Broken |
Stack<char> | Pushes every char, then pops into a StringBuilder | 896 B | Broken |
| Recursion | Joins the last char, the reversed middle and the first char | 5,736 B | Broken |
TextElementEnumerator | Copies whole text elements to mirrored positions | 152 B | Correct |
Only the last row handles every string. For plain text, the first two rows are the fastest, and string.Create() allocates half as much.
Conclusion
In this article, we examined various different methods that allow us to reverse a string. This included looking at a method that deals with combining or surrogate characters. Then, we evaluated our solutions in terms of performance and efficiency, determining which was the best choice for our requirements.
If you ever need to reverse the digits of a number, our article on reversing a number as an integer shows how to do it without turning it into a string first.
Tested with .NET 11.0.0, BenchmarkDotNet 0.15.8 and MSTest 4.5.3.






