Introduction
Reversing a string is a very basic but important concept in programming. It involves taking a string & transforming in such a way that characters are in reverse order. For example, if we have the string "hello", the reversed string would be "olleh". String reversal is often used in many situations, such as checking if a string is a palindrome or manipulating text data.
In this article, we will learn how to reverse a string in C# using different methods with proper examples.
Method 1: Using a For Loop to Reverse a String
One basic and easy way to reverse a string in C# is by using a for loop. This method uses the power of the loop to iterate over the string from the last character to the first, appending each character to a new string. Let’s see how we can implement this:
Working
- Initialize a New String: Start by creating an empty string that will hold the reversed characters.
- Iterate Backwards Through the Original String: Use a for loop to iterate from the end of the string to the beginning. You access each character by its index.
- Append Each Character: During each iteration, append the current character to the new string.
Example
string ReverseString(string input)
{
string reversed = "";
for (int i = input.Length - 1; i >= 0; i--)
{
reversed += input[i];
}
return reversed;
}
In this code, input.Length - 1 is the index of the last character in the string, & the loop continues until it reaches the first character (i >= 0). Each character from the input string is added to reversed in reverse order.
Explanation of the Code
- string reversed = "": Initializes a new string to collect the reversed characters.
- for (int i = input.Length - 1; i >= 0; i--): Starts from the last character & moves backward.
- reversed += input[i];: Appends the character at index i from the input string to the reversed string.
Note : This method is effective for shorter strings or situations where performance is not the primary concern, because string concatenation in a loop can be costly for very long strings.