In this C# tutorial, I have explained, how to reverse a string in C# using a for loop. I will show a complete example with the output.
Reverse a String in C# using a For Loop
Imagine you have a word, let’s say “HELLO”. If you were to write it backward, you’d get “OLLEH”. Essentially, reversing a string means you’re reading it from the end to the beginning.
Here is an example.
using System;
class Program
{
static void Main()
{
string original = "HELLO";
string reversed = ReverseString(original);
Console.WriteLine($"Original String: {original}");
Console.WriteLine($"Reversed String: {reversed}");
}
static string ReverseString(string str)
{
char[] charArray = str.ToCharArray(); // Convert string to character array
int length = charArray.Length;
char[] reversedArray = new char[length];
for (int i = 0; i < length; i++)
{
reversedArray[length - 1 - i] = charArray[i];
}
return new string(reversedArray);
}
}
Once you run the code, you can see the output below:
Code Explanation:
Here is the complete code explanation.
- Conversion to Character Array: Since strings in C# are immutable, it’s more convenient to convert the string to a character array using the
ToCharArray()
method.
char[] charArray = str.ToCharArray();
- Initialize the Reversed Array: Create a new character array of the same length to hold the reversed characters.
char[] reversedArray = new char[length];
- The For Loop: The idea here is to iterate over the
charArray
from the start to the end, but fill up thereversedArray
from the end to the start. Hence, for each character incharArray
, we calculate its corresponding position in the reversed array using the formulalength - 1 - i
.
for (int i = 0; i < length; i++)
{
reversedArray[length - 1 - i] = charArray[i];
}
- Convert Back to String: Once the characters are placed in the reversed order, convert the character array back to a string using the
string
constructor.
return new string(reversedArray);
This is the complete code to reverse a string in c# using for loop.
Conclusion
Reversing a string in C# using a for
loop is a straightforward process. It’s essential to understand the importance of using a character array, as it offers more flexibility for such manipulations, given that strings are immutable in C#.
You may like the following tutorials:
- Check if an Array is Empty in C#
- Dynamic Arrays in C# with Examples
- How to reverse string in C# using while loop?
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…