Sometimes we might need to reverse string letters order. unfortunately, String class in .Net Framework up to version 3.5 doesn’t have a Reverse Method. here I will try to add Reverse Extension Method to String class.
The idea behind string reverse is converting the string to an array of chars and then apply Array.Reverse() method and again convert the array of chars to string. see code
public string ReverseString(string originalString) { char[] strArray = originalString.ToCharArray(); Array.Reverse(strArray); string strReversed = new string(strArray); return strReversed; }
For simplicity, StringHelper class is created to provide string.Reverse method as Extension Method
public static class StringHelper { public static string ReverseString(string originalString) { char[] strArray = originalString.ToCharArray(); Array.Reverse(strArray); string strReversed = new string(strArray); return strReversed; } public static string Reverse(this string originalString) { char[] strArray = originalString.ToCharArray(); Array.Reverse(strArray); string strReversed = new string(strArray); return strReversed; } }
Easy to use
string str = "abcdef"; string ReversedStr = str.Reverse();
Happy Coding…
return new string(originalString.AsEnumerable().Reverse().ToArray());