Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Method 1: Using a For Loop to Reverse a String
2.1.
Working 
2.2.
Example
2.3.
Explanation of the Code
3.
Method 2: Using a While Loop to Reverse a String
3.1.
Working
3.2.
Example 
4.
Frequently Asked Questions
4.1.
Can these methods be used for strings with special characters or spaces?
4.2.
Which method is faster for reversing a string in C#?
4.3.
Is it necessary to use built-in functions to reverse a string in C#?
5.
Conclusion 
Last Updated: Jun 9, 2024
Easy

Reverse String in C#

Author Rahul Singh
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

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. 

Reverse String in C#

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Method 2: Using a While Loop to Reverse a String

Another important method to reverse a string in C# is by using a while loop, which can be particularly useful when you want to add additional conditions within the loop or prefer a different looping construct for better understanding. This method involves two pointers: one starting at the beginning of the string and the other at the end, swapping characters until they meet in the middle.

Working

  • Convert String to Char Array: Since strings in C# are immutable, convert the string into a character array for easy manipulation.
     
  • Initialize Pointers: Set up two pointers, one at the beginning (start) and one at the end (end) of the array.
     
  • Swap Characters: Use the while loop to swap characters at the start and end pointers until they meet or cross each other.

Example 

string ReverseStringUsingWhile(string input)
{
    char[] charArray = input.ToCharArray();
    int start = 0;
    int end = input.Length - 1;
    while (start < end)
    {
        // Swap characters
        char temp = charArray[end];
        charArray[end] = charArray[start];
        charArray[start] = temp;
        
        // Move pointers towards the center
        start++;
        end--;
    }
    return new string(charArray);
}

Explanation 

  1. char[] charArray = input.ToCharArray();: Converts the input string into a mutable character array.
     
  2. int start = 0; int end = input.Length - 1;: Initializes the pointers at the start and end of the array.
     
  3. while (start < end): Continues to loop until the two pointers meet or cross.
     
  4. Inside the loop:
     
  • Characters are swapped between start and end.
     
  • Pointers are moved inward after each swap.
     

Note : This method is effective for longer strings as it operates in-place without the need for additional memory for string concatenation, unlike the for loop method.

Frequently Asked Questions

Can these methods be used for strings with special characters or spaces?

Yes, both methods handle strings with special characters & spaces effectively, as they treat all characters equally during the reversal process.

Which method is faster for reversing a string in C#?

The while loop method tends to be faster & more memory-efficient, especially for longer strings, because it works in-place without creating additional strings during the process.

Is it necessary to use built-in functions to reverse a string in C#?

While built-in functions like Array.Reverse() and string.Concat() can simplify the code, understanding these basic methods is crucial for strengthening your programming skills & customizing functionality as needed.

Conclusion 

In this article, we learned how to reverse a string in C# using two different methods: a for loop & a while loop. Both methods achieve the same result by iterating over the characters of the string in reverse order & building the reversed string character by character. String reversal is a common task in programming & learning these methods will help you manipulate strings effectively in your C#.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass