Reverse A String In C#
Code snippet for how to Reverse A String In C# with sample and detail explanation
One of the most common problems a programmer may come across is the need to reverse a string in C#. We won’t be using any inbuilt functions of C# for this purpose, rather we will be implementing this string reversal manually.
Code snippet for reversing a string in C#
using System;
class Program
{
static void Main()
{
string str = "Hello, World!";
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(charArray);
}
}
Code Explanation for reversing a string in C#
In the given code snippet, the basic idea is to convert the string into an array of characters, reverse that array, and then convert it back into a string.
-
First, we use the
using System;
directive which allows us to use classes from the System namespace without typing out their full names. -
We declare the class called Program. The Main method is the entry point for the program.
-
Inside the Main method, we declare a string
str
that contains the text “Hello, World!“. -
We then convert the
str
string into a character array using theToCharArray()
function from the string class in C#. This results in an array of individual characters from the string. -
After that, we use the
Array.Reverse()
function from the Array class in C#. This reverses the order of the characters in the array. -
Finally, we use the
Console.WriteLine(charArray);
statement to print out our reversed string to the console. -
When this code is executed, it reverses the string “Hello World!”, producing the output “!dlroW ,olleH”.
This is an easy, efficient and quick way to reverse a string in C# using built-in functions. You can apply this approach to any string you want to reverse, which makes it a useful utility in a wide variety of programming tasks.