String is commonly used data type.We can store different types of values in a string and then cast them to the appropriate data type.String is a sequence of characters and the value of an string can not be changed.Assigning a different value to a string creates a new string object.
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.
public static string Reverse(string stringToReverse ) { char[] stringArray = stringToReverse.ToCharArray(); string reverse = String.Empty; for(int i=stringArray.Length-1;i>=0;i--) { reverse += stringArray[i]; } return reverse; }
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.
public static string Reverse(string stringToReverse ) { char[] stringArray = stringToReverse.ToCharArray(); string reverse = String.Empty; Array.Reverse(stringArray); return new string(stringArray); }
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.
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.
Leave a Reply