How to reverse a string in C# using inbuilt function?

In this C# tutorial, I will let you know how to reverse a string in C# using inbuilt function with a complete example.

Reverse a string in C# using inbuilt function

First, let’s get one thing clear: Unlike some other programming languages, C# does not have a Reverse() method specifically for strings. However, it does offer the Reverse() method for arrays. Given that strings are essentially arrays of characters in C#, this comes in handy.

Steps to Reverse a String using Array.Reverse():

  1. Convert the string to a character array.
  2. Use the Array.Reverse() method.
  3. Convert the reversed character array back to a string.

Code Example:

using System;

namespace StringReversal
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputString = "Hello, World!";
            string reversedString = ReverseString(inputString);

            Console.WriteLine("Original String: " + inputString);
            Console.WriteLine("Reversed String: " + reversedString);

            Console.ReadKey();
        }

        static string ReverseString(string str)
        {
            // 1. Convert string to char array
            char[] charArray = str.ToCharArray();

            // 2. Use Array.Reverse() method
            Array.Reverse(charArray);

            // 3. Convert the reversed char array back to a string
            return new string(charArray);
        }
    }
}

Points to Remember:

  1. Even though we’re leveraging an inbuilt method, it’s crucial to understand the underlying process. Essentially, the string is treated as an array of characters.
  2. This method is both efficient and concise, making it an excellent choice for reversing strings in C#.
  3. It’s always good to wrap such functionality inside a separate utility function, like ReverseString, for reusability.

Once you run the above code, you can see the output below:

reverse string in c# using inbuilt function

Conclusion

While C# doesn’t offer a direct Reverse() method for strings, it does provide tools that make this task straightforward. By understanding the core of C# strings and the .NET Framework’s utilities, we can manipulate strings efficiently. I hope you got an idea of how to reverse a string in C# using inbuilt function.

You may also like: