Skip to content
Home » How To Reverse a String in C#

How To Reverse a String in C#

Spread the love

Sometimes you may need to reverse a string. How to do it in C#?

Actually, there are a couple ways you can reverse a string in C#. A fast and easy way to do it is by means of the built-in Reverse method on the Array class. As this method works on arrays, we first have to convert the string into an array. The example below was written in Visual Studio using the C# Interactive window.

Let’s first define a string to have something to work on:

> string text = "hello";

And now, let’s reverse it. So, here are the steps to follow:

1) Convert the string into an array of chars.

> char[] textChars = text.ToCharArray();

2) User the Reverse method on the array.

> Array.Reverse(textChars);

3) Return a new string created from the reversed characters.

> return new string(textChars);

Here’s the code again with the output at the end.

> char[] textChars = text.ToCharArray();
> Array.Reverse(textChars);
> return new string(textChars);
"olleh"

This can be rewritten as a one-liner as well:

> new string(text.ToCharArray().Reverse().ToArray())
"olleh"

Let’s write and call a function that tests if a string is a palindrome. It is if it reads the same in both directions, like “gig” or “kayak”. You can neglect capitalization and white spaces:

internal class Program
{
    public static bool isPalindrome(string text)
    {
        // Set all characters to lowercase.
        string textLowerCase = text.ToLower();

        // Remove whitespaces.
        string textNoSpaces = textLowerCase.Replace(" ", "");

        // Check if the string is a palindrome.
        return new string(textNoSpaces.ToCharArray().Reverse().ToArray()) == textNoSpaces;
    }

    static void Main()
    {
        string[] stringsToCheck = { "hello", "A Santa at Nasa" };

        for (int i = 0; i < stringsToCheck.Length; i++)
        {
            string stringToCheck = stringsToCheck[i];

            if (isPalindrome(stringToCheck))
            {
                Console.WriteLine($"'{stringToCheck}' is a palindrome.");
            }
            else
            {
                Console.WriteLine($"'{stringToCheck}' is not a palindrome.");
            }
        }
    }
}

Output:

'hello' is not a palindrome.
'A Santa at Nasa' is a palindrome. 

As you can see, there’s no magic involved. If you want to play with this function a bit more, here are some palindromes that you can test. They should all give you a positive result:

deed, radar, level, civic, racecar

I’m sure you can come up with some more of your own.


Spread the love

Leave a Reply