C# Reverse String

You want to reverse the individual characters in a string in your program targeting the .NET Framework. You may use this method in a loop thousands of times, so performance is important, but you also need to review it quickly. Here we see how you can efficiently reverse the characters in a string in the C# programming language.
Input:

[1] framework
[2] samuel
[3] example string

Output:

[1] krowemarf
[2] leumae
[3] gnirts elpmaxe

Example

First, there are many solutions, but this one can be done with three lines of code. The method shown in this article is based on my work with ToCharArray, and the method is static because it does not need to save state.
Example program that reverses strings [C#]

using System;

static class StringHelper
{
    /// <summary>
    /// Receives string and returns the string with its letters reversed.
    /// </summary>
    public static string ReverseString(string s)
    {
 char[] arr = s.ToCharArray();
 Array.Reverse(arr);
 return new string(arr);
    }
}

class Program
{
    static void Main()
    {
 Console.WriteLine(StringHelper.ReverseString("framework"));
 Console.WriteLine(StringHelper.ReverseString("samuel"));
 Console.WriteLine(StringHelper.ReverseString("example string"));
    }
}

Output

krowemarf
leumas
gnirts elpmaxe
Overview. The method above receives a string parameter, which is the string in which you wish to reverse the order of the letters. The method is static because it doesn't store state. It calls the static Array method called Reverse to modify the order of the chars.
Array.Reverse Inverts Array OrderingControl flow of method. It copies to an array using the ToCharArray instance method on the string class. This returns the mutable char[] buffer from the string. It returns a string with the new string constructor, which we pass the char[] buffer to. This is our final reversed string.
ToCharArray Method, Convert String to ArrayPerformance optimization

Performance

Here we note the performance characteristics of the method. Using ToCharArray on strings for modifications is often quite efficient. Justin Rogers from Microsoft offers some detailed benchmarking.
weblogs.asp.net

Summary

Here we saw a method that can receive a string and then return the string with its characters in the reverse order. It is one of many examples of using char[] arrays for string manipulation in the C# language. The code isn't useful often, but it may help for an interview question or two. This article is found in the Sorting category on Dot Net Perls.

0 comments:

Post a Comment