Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to display a string in reverse alphabetic order
To display a string in reverse order, you can convert the string to a character array and then use the Array.Reverse() method. This approach reverses the order of characters, displaying them from last to first.
Syntax
Following is the syntax for converting a string to character array −
char[] arr = str.ToCharArray();
Following is the syntax for reversing the array −
Array.Reverse(arr);
Using Array.Reverse() Method
The simplest approach is to convert the string to a character array and use Array.Reverse() to reverse the order of characters −
using System;
class Program {
static void Main() {
string str = "Amit";
char[] arr = str.ToCharArray();
Console.WriteLine("Original String: " + str);
// Reverse the character array
Array.Reverse(arr);
Console.WriteLine("Reversed String: " + new string(arr));
}
}
The output of the above code is −
Original String: Amit Reversed String: timA
Using LINQ Reverse() Method
You can also use LINQ's Reverse() method with string.Concat() to achieve the same result −
using System;
using System.Linq;
class Program {
static void Main() {
string str = "Programming";
Console.WriteLine("Original String: " + str);
// Using LINQ Reverse
string reversed = string.Concat(str.Reverse());
Console.WriteLine("Reversed String: " + reversed);
}
}
The output of the above code is −
Original String: Programming Reversed String: gnimmargorP
Using Loop Method
You can manually reverse a string using a for loop by iterating from the last character to the first −
using System;
class Program {
static void Main() {
string str = "Hello";
string reversed = "";
Console.WriteLine("Original String: " + str);
// Loop from last character to first
for (int i = str.Length - 1; i >= 0; i--) {
reversed += str[i];
}
Console.WriteLine("Reversed String: " + reversed);
}
}
The output of the above code is −
Original String: Hello Reversed String: olleH
Comparison of Methods
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| Array.Reverse() | Fast | High | Moderate |
| LINQ Reverse() | Moderate | Very High | Higher |
| Loop Method | Slower for large strings | Moderate | Higher (string concatenation) |
Conclusion
There are multiple ways to reverse a string in C#. The Array.Reverse() method is the most efficient approach, while LINQ provides the most readable solution. Choose the method that best fits your performance requirements and coding style preferences.
