A common requirement is reversing strings in c#.There are few different ways by which we can reverse strings.
Using the for loop for reversing strings
We iterate over the entire string and then just assign the characters to a different string.We loop through the original string in reverse order.
Using the Reverse method of the array class
Reverse is a static method of the Array class.We can pass char array to this method and it will reverse the order of the characters.Once we get the characters in reverse order we can pass them to the string constructor to create the reversed string.
Reversing strings in c# using LINQ
We can use the query operators in LINQ to reverse the strings.For reversing strings in c# using linq we use the ForEach() method which iterates over the entire collection.In this method we pass the logic to reverse the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public static string Reverse(string stringToReverse )
{
//calculate length of the string
int length=stringToReverse.Length-1;
//create character array of the size of the string
char[] reverseString = new char[length+1];
//loop through the original string and assign elements in reverse order
stringToReverse.ToCharArray().ToList().ForEach
(
x =>
{
reverseString[length] = x;
length=length - 1;
}
);
return new string(reverseString);
}
|
By using the ForEach method we can avoid the for statement and directly loop over the string.
No comments:
Post a Comment