Reverse of a String without using String Reverse Function-Alternate Tips

RaviRanjanKr
Posted by RaviRanjanKr under C# category on | Points: 40 | Views : 3619
In alternate of This tips-[ http://www.dotnetfunda.com/codes/code1684-reverse-of-a-string-without-using-string-reverse-function.aspx ]
we have various ways to use Reverse a string without using any function.
take a look at given ways

Way 1 :-its better to using LINQ
public static string ReverseString(string str)
{
return new string(Enumerable.Range(1, str.Length).Select(i => str[str.Length - i]).ToArray());
}



Ways 2: - Using bitwise XOR
public static string ReverseXor(string s)
{
char[] charArray = s.ToCharArray();
int len = s.Length - 1;
for (int i = 0; i < len; i++, len--)
{
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
}
return new string(charArray);
}


Ways 3:- recursive approach
 private static string Reverse(string str)
{
if (str.Length == 1)
return str;
else
return str[str.Length - 1] + Reverse(str.Substring(0, str.Length - 1));
}


Way 4 :- flexible way
public static string Reverse(string x)
{
char[] charArray = new char[x.Length];
int len = x.Length - 1;
for (int i = 0; i <= len; i++)
charArray[i] = x[len - i];
return new string(charArray);
}


apart of all these method I will recommend myself to use Array.Reverse() function and LINQ

Comments or Responses

Posted by: Ndebata on: 7/24/2011 Level:Starter | Status: [Member] | Points: 10
No need to loop all the elements , you can do half way :)
string str = "12345";

char[] charr = str.ToCharArray();
for (int i = 0; i < charr.Length/2; i++)
{
char ctemp = charr[i];
charr[i] = charr[charr.Length - 1 - i];
charr[charr.Length - 1 - i] = ctemp;
}
str=new string(charr);


Thanks,
Narayan
Posted by: RaviRanjanKr on: 7/25/2011 Level:Starter | Status: [Member] | Points: 10
yeah! Its takes minimum traversal to reverse string.
I checked to reverse "12345" and it takes only 6 traversal where as Mine take 62.
so well using half length working nice here.
after all a big thanks to share it :)

Posted by: Gsudhesh on: 7/27/2011 Level:Starter | Status: [Member] | Points: 10
very useful snippet
Posted by: RaviRanjanKr on: 7/28/2011 Level:Starter | Status: [Member] | Points: 10
I am glad you Liked it. :)

Login to post response