-2

I have wrote this extension function to reverse the single string value. I think I can short it more please suggest.

public static string ReverseSingleString(this string value)
        {
            string newString = string.Empty;
            char[] chars = new char[value.Length];
            char[] chars2 = new char[value.Length];
            int j = 0;
            foreach (char c in value)
            {
                chars[j] = c;
                j++;
            }
            j = 0;
            for (int i = chars.Length - 1; i >= 0; i--)
            {
                chars2[j] = chars[i];
                newString += chars2[j].ToString();
                j++;
            }
            return newString;
        }
dawncode
  • 578
  • 1
  • 8
  • 22
  • 3
    This question appears to be off-topic because it is about code review. http://codereview.stackexchange.com/ – dee-see Feb 05 '14 at 15:33
  • possible duplicate of [Best way to reverse a string](http://stackoverflow.com/questions/228038/best-way-to-reverse-a-string) – Tim Schmelter Feb 05 '14 at 15:49

4 Answers4

4

How about following extension

public static class StringExtensions{
   public static string ReverseString (this string value) 
   {
       var reversed = string.Join("",value.Reverse());
       return reversed;
   }
}
tchrikch
  • 2,428
  • 1
  • 23
  • 43
3

Without any reverse function:

string Reverse(string s)
{
    char[] c = new char[s.Length];
    for (int i = s.Length-1, j = 0; i >=0 ; i--, j++)
    {
        c[j] = s[i];
    }
    return new string(c);
}

obviously you can put that in an extension method

Alberto
  • 15,626
  • 9
  • 43
  • 56
2

Since it's an extension and i don't need to care about readability, i would use a StringBuilder:

public static string ReverseSingleString(this string value)
{
    StringBuilder sb = new StringBuilder(value.Length);
    for(int i = value.Length - 1; i >= 0; i--)
        sb.Append(value[i]);
    return sb.ToString();
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Also you can use Array.Reverse method

public static string Reverse(this string source)
{
    var chars = source.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184