Efficiently create reverse copy of a string in C#
This article illustrates the different techniques to efficiently create a reverse copy of a string in C#.
1. Using Array.Reverse() method
We can use Array.reverse() to create a reverse copy of a string in C#. The idea is to convert the given string into a character array using the String.toCharArray() method, and reverse the array using the Array.Reverse() method. Then, convert the character array back into a string using the String constructor and return it. The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; public static class StringExtensions { public static string Reverse(this string str) { char[] chars = str.ToCharArray(); Array.Reverse(chars); return new string(chars); } } public class Example { public static void Main() { string str = "Hello World"; string rev = str.Reverse(); Console.WriteLine(rev); } } |
2. Using String.Create() method
Starting with .NET 6, you can use the String.Create() method to reverse a string. It creates a new string with a specific length and initializes it after creation by using the specified callback. The following example demonstrates its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Linq; public static class StringExtensions { public static string Reverse(this string str) { return string.Create<string>(str.Length, str, (c, s) => { s.AsSpan().CopyTo(c); c.Reverse(); }); } } public class Example { public static void Main() { string str = "Hello World"; string rev = str.Reverse(); Console.WriteLine(rev); } } |
That’s all about efficiently creating a reverse copy of a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)