{"id":89415,"date":"2023-05-18T08:00:52","date_gmt":"2023-05-18T06:00:52","guid":{"rendered":"https:\/\/code-maze.com\/?p=89415"},"modified":"2023-05-18T14:19:11","modified_gmt":"2023-05-18T12:19:11","slug":"csharp-reverse-string","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-reverse-string\/","title":{"rendered":"How to Reverse a String in C#"},"content":{"rendered":"<p>Reversing a string is a common task in programming, and C# provides several ways to accomplish it. Whether we need to reverse a string for <a href=\"https:\/\/code-maze.com\/sorting-algorithms-csharp\/\" target=\"_blank\" rel=\"noopener\">sorting<\/a> purposes, to improve search efficiency, or for any other reason, understanding how to perform this operation in C# is an essential skill.<\/p>\n<p>In this article, we will examine several techniques to reverse a string in C# and compare their performance to help you choose the best approach for your specific use case.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/strings-csharp\/StringReverse\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let\u2019s start!<\/p>\n<h2>Application Setup<\/h2>\n<p>To explore ways to reverse a string in C#. let&#8217;s start by creating a console application using the Visual Studio Project wizard or the\u00a0<code>dotnet new console<\/code> command.<\/p>\n<p>For each solution, we will create a method that takes a string as an argument and returns one, too.<\/p>\n<p>Some of the techniques we propose involve <strong>creating a new string or data structure to hold the reversed characters, while others work by manipulating the existing string in place.<\/strong> 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.<\/p>\n<p>We&#8217;ll start by setting up a simple example to test against our methods:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var input = \"abcdefg\";<\/code><\/p>\n<p>We construct a simple string using <strong>the first seven letters of the Latin alphabet<\/strong> and we expect to return the letters in reversed order: <code>\"gfedcba\"<\/code>.<\/p>\n<h2>Use Array.Reverse() Method to Reverse a String<\/h2>\n<p>The first method to reverse a string we&#8217;ll look at is the <code>Reverse()<\/code> method from the <code>Array<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string ArrayReverseString(string stringToReverse)\r\n{\r\n    var charArray = stringToReverse.ToCharArray();\r\n    Array.Reverse(charArray);\r\n\r\n    return new string(charArray);\r\n}<\/pre>\n<p>First, we convert the input\u00a0string into a character array using the <code>ToCharArray()<\/code>\u00a0method provided by the <code>string<\/code> class in C#. This method splits a string into its constituent characters and stores them in a <code>char[]<\/code>.<\/p>\n<p>Next, we use the <code>Reverse()<\/code> method to reverse the order of the elements in the <code>charArray<\/code> collection.<\/p>\n<p>Finally, we convert the reversed <code>charArray<\/code> back into a <code>string<\/code> using the string constructor that takes an array of characters as input and we return it.<\/p>\n<p>The result is the following:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Reversed String: gfedcba<\/code><\/p>\n<p>As we expect, the result is the initial string&#8217;s characters in reverse order.<\/p>\n<h2>Enumerable Reverse() Extension Method for String Reversion<\/h2>\n<p>Our next solution uses the <code>Reverse()<\/code> extension method of the <code>Enumerable<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string EnumerableReverseMethod(string stringToReverse)\r\n{\r\n    return string.Concat(Enumerable.Reverse(stringToReverse));\r\n}<\/pre>\n<p>The <code>Enumerable.Reverse()<\/code> method takes a collection (in this case, a string) and returns an <code>IEnumerable&lt;char&gt;<\/code>. Here, it represents <strong>a sequence of characters in reverse order.<\/strong><\/p>\n<p>To convert the reversed sequence of characters back into a string, we use the <code>string.Concat()<\/code> method, which concatenates a sequence of characters into a single string.<\/p>\n<p>In this case, we pass the reversed sequence to create a new string with the characters in reverse order.<\/p>\n<h2>Reverse a String With Recursion<\/h2>\n<p>Another option for reversing a string is to use <a href=\"https:\/\/code-maze.com\/csharp-basics-recursion\/\" target=\"_blank\" rel=\"noopener\">recursion<\/a>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string RecursiveStringReverseMethod(string stringToReverse)\r\n{\r\n    if (stringToReverse.Length &lt;= 1)\r\n        return stringToReverse;\r\n\r\n    return stringToReverse[^1] + \r\n           RecursiveStringReverseMethod(stringToReverse[1..^1]) + stringToReverse[0];\r\n}<\/pre>\n<p>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.<\/p>\n<p>Otherwise, we call the <code>RecursiveStringReverseMethod()<\/code> method recursively, passing in the substring of the input string each time, excluding the first and last characters using the <code><span style=\"font-weight: 400;\">stringToReverse<\/span>[1..^1]<\/code> object. We return the concatenation of the last character of the input <code>substring<\/code> (<code><span style=\"font-weight: 400;\">stringToReverse<\/span>[^1]<\/code>), the result of the recursive call, and the first character of the input string (<code><span style=\"font-weight: 400;\">stringToReverse<\/span>[0]<\/code>).<\/p>\n<p>In C# 8.0, two new concepts were introduced, <a href=\"https:\/\/code-maze.com\/csharp-ranges-and-indices\/\" target=\"_blank\" rel=\"noopener\">Ranges and Indices<\/a>. The <code>[^1]<\/code> is called a slice notation and represents an index relative to the end of the string. In other words, <code>s[^1]<\/code> is equivalent to <code><span style=\"font-weight: 400;\">stringToReverse<\/span>[<span style=\"font-weight: 400;\">stringToReverse<\/span>.Length - 1]<\/code>, which accesses the last character of the string.<\/p>\n<p>The <code>[1..1^]<\/code> syntax specifies a range that starts at the second character and ends at the second-to-last character. The <code>^<\/code> symbol represents an index relative to the end of the string. In this case, <code>1^<\/code> means one index from the end of the string.<\/p>\n<p>This effectively <strong>reverses the input string<\/strong> <strong>using recursion<\/strong>.<\/p>\n<h2>Reverse a String Using a Loop and XOR Operator<\/h2>\n<p>Now we will utilize the XOR operator within iterations to reverse our string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string ReverseXorMethod(string stringToReverse)\r\n{\r\n    var charArray = stringToReverse.ToCharArray();\r\n    var len = stringToReverse.Length - 1;\r\n\r\n    for (int i = 0; i &lt; len; i++, len--)\r\n    {\r\n        charArray[i] ^= charArray[len];\r\n        charArray[len] ^= charArray[i];\r\n        charArray[i] ^= charArray[len];\r\n    }\r\n\r\n    return new string(charArray);\r\n}<\/pre>\n<p>First, we convert the string into a <code>char[]<\/code>\u00a0and initialize an integer variable <code>len<\/code> to the length of the input string minus one.<\/p>\n<p>We use a loop to swap the characters at the beginning and end of the <code>charArray<\/code>, 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 <code>i<\/code> and <code>len<\/code> index. The <code>^=<\/code> operator is the XOR assignment operator. It performs the XOR operation on the two operands and assigns the result to the left operand.<\/p>\n<p>Once the loop completes the iterations, the <code>charArray<\/code> contains the reversed string. Finally, we return a new string from the reversed <code>charArray<\/code>.<\/p>\n<h2>Use Stack to Reverse a String<\/h2>\n<p>Next, we can use the <a href=\"https:\/\/code-maze.com\/stack-csharp\/\" target=\"_blank\" rel=\"noopener\">Stack<\/a> class, which is a last-in, first-out (LIFO) stack of objects, to reverse a string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string StackReverseMethod(string stringToReverse)\r\n{\r\n    var resultStack = new Stack&lt;char&gt;();\r\n    foreach (char c in stringToReverse)\r\n    {\r\n        resultStack.Push(c);\r\n    }\r\n\r\n    var sb = new StringBuilder();\r\n    while (resultStack.Count &gt; 0)\r\n    {\r\n        sb.Append(resultStack.Pop());\r\n    }\r\n\r\n    return sb.ToString();\r\n}<\/pre>\n<p>Here, we iterate the input string <code><span style=\"font-weight: 400;\">stringToReverse<\/span><\/code>\u00a0character by character using a <code>foreach<\/code> loop, and we push each character onto a <code>resultStack<\/code> stack. This means that we add the characters to the stack in reverse order, effectively reversing the string.<\/p>\n<p>We create a new <a href=\"https:\/\/code-maze.com\/stringbuilder-csharp\/\" target=\"_blank\" rel=\"noopener\">StringBuilder<\/a> object to construct the reversed string by popping characters from the stack and appending them to the <code>StringBuilder<\/code>. The <code>while<\/code> loop continues to pop characters from the stack and append them to the <code>StringBuilder<\/code> until there are no more characters left in the stack.<\/p>\n<p>Finally, we return the reversed string by calling the <code>ToString()<\/code> method on the <code>StringBuilder<\/code> object.<\/p>\n<h2>StringBuilder Method to Reverse a String<\/h2>\n<p>Alternatively, we can use the <code>StringBuilder<\/code> class directly to reverse a string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string StringBuilderReverseMethod(string stringToReverse)\r\n{\r\n    var sb = new StringBuilder(stringToReverse.Length);\r\n    for (int i = stringToReverse.Length - 1; i &gt;= 0; i--)\r\n    {\r\n        sb.Append(stringToReverse[i]);\r\n    }\r\n\r\n    return sb.ToString();\r\n}<\/pre>\n<p>First, we create a new <code>StringBuilder<\/code>\u00a0object with an initial capacity equal to the length of the input string <code><span style=\"font-weight: 400;\">stringToReverse<\/span><\/code>. With this, we ensure that the <code>StringBuilder<\/code> has enough space to hold the entire reversed string without needing to resize the buffer.<\/p>\n<p>Next, we iterate over the characters in the input string in reverse order using a <code>for<\/code> loop. In each iteration of the loop, the method appends the current character\u00a0using the <code>Append()<\/code> method. This effectively adds the characters to the <code>StringBuilder<\/code> in reverse order, so that the final result is the desired one.<\/p>\n<p>Finally, we return the string by calling the <code>ToString()<\/code> method on the <code>StringBuilder<\/code> object.<\/p>\n<h2>Use Create() Method to Create a String in Reverse Order<\/h2>\n<p>The <code>Create()<\/code> extension method of the <code>string<\/code> class can be used for the same purpose:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string StringCreateMethod(string stringToReverse)\r\n{\r\n    return string.Create(stringToReverse.Length, stringToReverse, (chars, state) =&gt;\r\n    {\r\n        state.AsSpan().CopyTo(chars);\r\n        chars.Reverse();\r\n    });\r\n}<\/pre>\n<p>Here, we use the <code>string.Create()<\/code> method to create a new string that is a reversed version of the input string <code><span style=\"font-weight: 400;\">stringToReverse<\/span><\/code>. The <code>string.Create()<\/code> 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 is responsible for initializing the string and returning it.<\/p>\n<p>In this method, the state object is the input <code><span style=\"font-weight: 400;\">stringToReverse<\/span><\/code> string, which is passed to the <code>string.Create()<\/code> method as the second argument. We define the callback function as an anonymous method that takes two parameters: <code>chars<\/code> and <code>state<\/code>. The <code>chars<\/code> object is a <a href=\"https:\/\/code-maze.com\/csharp-span-to-improve-application-performance\/\" target=\"_blank\" rel=\"noopener\">span<\/a> of characters that represents the newly created string, and the <code>state<\/code> is the original input string.<\/p>\n<p>The first line of the callback function copies the characters of the input string to the new string using the <code>CopyTo()<\/code> method of the <code>Span&lt;char&gt;<\/code> struct. This initializes the new string to be the same as the input string.<\/p>\n<p>The second line of the callback function reverses the order of the characters in the <code>chars<\/code> object using the <code>Reverse<\/code> method of the <code>Span&lt;char&gt;<\/code> <a href=\"https:\/\/code-maze.com\/csharp-structures\/\" target=\"_blank\" rel=\"noopener\">struct<\/a>. This effectively reverses the order of the characters in the new string, giving us our final reversed string.<\/p>\n<h2>LINQ Reverse() Extension Method<\/h2>\n<p>The last solution we&#8217;ll look at uses the built-in <code>Reverse()<\/code> extension method of <code>string<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string StringExtensionReverseMethod(string stringToReverse)\r\n{\r\n    return new string(stringToReverse.Reverse().ToArray());\r\n}<\/pre>\n<p>Here, we use the <a href=\"https:\/\/code-maze.com\/linq-csharp-basic-concepts\/\" target=\"_blank\" rel=\"noopener\">LINQ<\/a> <code>Reverse()<\/code> extension method and the <code>ToArray()<\/code> method to create a new string that is a reversed version of the input string <code>stringToReverse<\/code>.<\/p>\n<p>We use the <code>string<\/code> constructor to create a new string from the reversed character array and we return it.<\/p>\n<h2>Special Characters Reversion With TextElementEnumerator<\/h2>\n<p>Sometimes we need to manipulate a string consisting of combining characters or <a href=\"https:\/\/learn.microsoft.com\/en-us\/globalization\/encoding\/surrogate-pairs\" target=\"_blank\" rel=\"nofollow noopener\">surrogate pairs<\/a>. These strings do not have a valid representation in Unicode. In this case, <strong>we cannot handle them character by character<\/strong>, as they consist of a sequence of several Unicode values.<\/p>\n<p>For example, each character of a music notes collection (e.g. \ud834\udd5e\ud834\udd1e\ud834\udd60\ud834\udd61) is a surrogate pair. We use the following approach to reverse it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string TextElementEnumeratorMethod(string stringToReverse)\r\n{\r\n    return string.Create(stringToReverse.Length, stringToReverse, (chars, val) =&gt;\r\n    {\r\n        var valSpan = val.AsSpan();\r\n        var en = StringInfo.GetTextElementEnumerator(val);\r\n        en.MoveNext();\r\n        var start = en.ElementIndex;\r\n        var pos = chars.Length;\r\n        while (en.MoveNext())\r\n        {\r\n            var next = en.ElementIndex;\r\n            var len = next - start;\r\n            valSpan[start..next].CopyTo(chars[(pos - len)..pos]);\r\n            pos -= len;\r\n            start = next;\r\n        }\r\n\r\n        if (start != 0)\r\n            valSpan[start..].CopyTo(chars[0..pos]);\r\n    });\r\n}<\/pre>\n<p>We use the <code>string.Create()<\/code> method to efficiently create a new string with a specified length and content. The <code>chars<\/code> parameter of the <code>Create()<\/code> method is a span of characters to write to. The <code>val<\/code> parameter is the value of the input string.<\/p>\n<p>We create a <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.globalization.textelementenumerator?view=net-8.0\" target=\"_blank\" rel=\"nofollow noopener\">TextElementEnumerator<\/a> object using the <code>StringInfo.GetTextElementEnumerator()<\/code> method, passing in the <code>val<\/code> parameter but this time as <a href=\"https:\/\/code-maze.com\/csharp-span-to-improve-application-performance\/\" target=\"_blank\" rel=\"noopener\">Span since it will increase the performance<\/a> of this approach compared to the same approach without it. This object allows us to enumerate over the text elements of <code>val<\/code>.<\/p>\n<p>Then, we iterate over the text elements in reverse order, copying each one to the new string.<\/p>\n<p>First, we get the index of the current text element using the <code>ElementIndex<\/code> property of the <code>TextElementEnumerator<\/code>, and we calculate the length of the text element by subtracting the index of the previous text element.<\/p>\n<p>Next, we use the <code>CopyTo()<\/code> method\u00a0to copy the text element to the appropriate position in the new string, which is given by the <code>chars<\/code> span. To calculate its position, we use the <code>pos<\/code> variable, which starts at the end of the new string and is decremented by the length of each text element.<\/p>\n<p>Finally, if there are any remaining characters in the <code>val<\/code> variable after all the text elements have been processed, the method copies them to the beginning of the new string.<\/p>\n<h2>What\u2019s the Fastest Way to Reverse a String in C#?<\/h2>\n<p>Let&#8217;s evaluate these methods to find the most efficient one with the <a href=\"https:\/\/code-maze.com\/benchmarking-csharp-and-asp-net-core-projects\/\" target=\"_blank\" rel=\"noopener\">benchmark<\/a> class. First, let&#8217;s create a method to generate a random string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string GenerateText()\r\n{\r\n    var alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\r\n    var random = new Random();\r\n    var length = 64;\r\n    var builder = new StringBuilder(length);\r\n\r\n    for (int i = 0; i &lt; length; ++i)\r\n    {\r\n        var index = random.Next(alphabet.Length);\r\n\r\n        builder.Append(alphabet[index]);\r\n    }\r\n\r\n    return builder.ToString();\r\n}<\/pre>\n<p>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.<\/p>\n<p>Now we&#8217;re ready to run and analyze our benchmark results:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">| Method                                  | Mean        | Error     | StdDev    | Rank |\r\n|---------------------------------------- |------------:|----------:|----------:|-----:|\r\n| UsingStringCreateMethod                 | 29.12 ns    | 0.221 ns  | 0.207 ns  | 1    |\r\n| UsingArrayReverseString                 | 43.41 ns    | 0.874 ns  | 0.935 ns  | 2    |\r\n| UsingReverseXorMethod                   | 90.88 ns    | 1.657 ns  | 2.322 ns  | 3    |\r\n| UsingStringBuilderReverseMethod         | 188.03 ns   | 3.429 ns  | 3.040 ns  | 4    |\r\n| UsingStackReverseMethod                 | 575.88 ns   | 8.609 ns  | 8.456 ns  | 5    |\r\n| UsingStringExtensionReverseMethod       | 637.23 ns   | 12.507 ns | 12.844 ns | 6    |\r\n| UsingEnumerableReverseMethod            | 933.08 ns   | 17.696 ns | 18.172 ns | 7    |\r\n| UsingRecursiveStringReverseMethod       | 1,670.41 ns | 32.406 ns | 47.500 ns | 8    |\r\n| UsingTextElementEnumeratorReverseMethod | 2,253.07 ns | 17.249 ns | 16.135 ns | 9    |<\/pre>\n<p>We can see that when it comes to reversing a string, <strong>the <code>StringCreateMethod()<\/code> method <\/strong><strong>is the most efficient in terms of speed.\u00a0<\/strong><\/p>\n<p>The <code>StringCreateMethod()<\/code> method is the <strong>fastest because it takes advantage of <code>Span&lt;T&gt;<\/code> and directly accesses the memory buffer of the original string, rather than creating a new copy of it.<\/strong> By using the <code>string.Create()<\/code> method and a user-defined delegate that operates on a <code>Span&lt;T&gt;<\/code>, we can efficiently initialize the reversed string in the same memory buffer as the original string.<\/p>\n<p>This<strong> avoids the overhead of allocating a new string and copying the characters into it<\/strong>, making the <code>StringCreateMethod()<\/code> method option faster than the other methods that create new copies of the string or using a loop.<\/p>\n<p>Moreover, we observe that the <code>ArrayReverseString()<\/code> method is similarly efficient. This is because the character array is directly modified in place without creating a new object.<\/p>\n<p>In contrast, the <code>RecursiveStringReverseMethod()<\/code> method has poor results as each recursive call to the method involves multiple string concatenations to build the final reversed string.<\/p>\n<p>Regarding the <code>TextElementEnumeratorMethod()<\/code> method, we&#8217;ve tested it and found that for the increased string size, the efficiency of this method grows and even gets better than the recursive one. <strong>It is worth mentioning though, that <code>TextElementEnumeratorMethod()<\/code> method solves the problem of reversing a string including characters that combine Unicode values and not usual characters.<\/strong><\/p>\n<h2>Conclusion<\/h2>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Reversing a string is a common task in programming, and C# provides several ways to accomplish it. Whether we need to reverse a string for sorting purposes, to improve search efficiency, or for any other reason, understanding how to perform this operation in C# is an essential skill. In this article, we will examine several [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[1510,1783,242],"class_list":["post-89415","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-c-strings","tag-reverse","tag-string","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Reverse a String in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we explore some of the different ways we can reverse a string in C#, benchmarking which method is the fastest.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-reverse-string\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Reverse a String in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we explore some of the different ways we can reverse a string in C#, benchmarking which method is the fastest.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-reverse-string\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-18T06:00:52+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-18T12:19:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Reverse a String in C#\",\"datePublished\":\"2023-05-18T06:00:52+00:00\",\"dateModified\":\"2023-05-18T12:19:11+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/\"},\"wordCount\":1906,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"C# strings\",\"reverse\",\"String\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-reverse-string\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/\",\"url\":\"https:\/\/code-maze.com\/csharp-reverse-string\/\",\"name\":\"How to Reverse a String in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2023-05-18T06:00:52+00:00\",\"dateModified\":\"2023-05-18T12:19:11+00:00\",\"description\":\"In this article, we explore some of the different ways we can reverse a string in C#, benchmarking which method is the fastest.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-reverse-string\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-reverse-string\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Reverse a String in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Reverse a String in C# - Code Maze","description":"In this article, we explore some of the different ways we can reverse a string in C#, benchmarking which method is the fastest.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-reverse-string\/","og_locale":"en_US","og_type":"article","og_title":"How to Reverse a String in C# - Code Maze","og_description":"In this article, we explore some of the different ways we can reverse a string in C#, benchmarking which method is the fastest.","og_url":"https:\/\/code-maze.com\/csharp-reverse-string\/","og_site_name":"Code Maze","article_published_time":"2023-05-18T06:00:52+00:00","article_modified_time":"2023-05-18T12:19:11+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Reverse a String in C#","datePublished":"2023-05-18T06:00:52+00:00","dateModified":"2023-05-18T12:19:11+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/"},"wordCount":1906,"commentCount":2,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["C# strings","reverse","String"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-reverse-string\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-reverse-string\/","url":"https:\/\/code-maze.com\/csharp-reverse-string\/","name":"How to Reverse a String in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2023-05-18T06:00:52+00:00","dateModified":"2023-05-18T12:19:11+00:00","description":"In this article, we explore some of the different ways we can reverse a string in C#, benchmarking which method is the fastest.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-reverse-string\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-reverse-string\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Reverse a String in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/89415","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=89415"}],"version-history":[{"count":4,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/89415\/revisions"}],"predecessor-version":[{"id":89983,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/89415\/revisions\/89983"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=89415"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=89415"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=89415"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}