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():
- Convert the string to a character array.
- Use the
Array.Reverse()
method. - 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:
- 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.
- This method is both efficient and concise, making it an excellent choice for reversing strings in C#.
- 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:
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:
- Single Dimensional Array in C# with Example
- How to reverse a string in C# using Linq?
- How to reverse string in C# using while loop?
- Convert String to Byte Array in C#
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…