C# Reverse String

Reverse

A string can be reversed. A reversal method can be implemented in several ways. Some ways are faster than others. And some use more lines of code—they are more complex to understand. We review and time one method.

Required input, output

framework        krowemarf
example string   gnirts elpmaxe

Example

Method call

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. It is static because it stores no state.

ToCharArray
Based on:

.NET 4

C# program that reverses strings

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
Static

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 Array.Reverse to modify the order of the chars.

Static MethodArray.Reverse

Control 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.

Char ArrayString ConstructorPerformance optimization

Performance:Using ToCharArray on strings for modifications is often efficient. Many benchmarks support this statement.

Summary

The C# programming language

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.

Note:The code isn't useful often. It may help for an interview question or two.


C#: Sort