0

I'm trying to reverse and return a StringBuilder result but I get the following errors for trying all variations in order of return sb.Reverse().ToString():

  1. Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string'.

  2. 'StringBuilder' does not contain a definition for 'Reverse' and no extension method 'Reverse' accepting a first argument of type 'StringBuilder' could be found

What is the proper format for returning the stringbuilder result in reverse order?

public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

This bit of code unfortunately doesn't do it one line

Please vote to delete this post so I can get rep back XD

springathing
  • 425
  • 3
  • 8
  • 28
  • Did you get confused with Java's `StringBuilder.Reverse()`? There's no such method in .NET. – Camilo Terevinto Dec 22 '17 at 15:31
  • It's not _entirely_ clear what you're after - do you want to reverse the resulting string, or do you want a string that contains the reverse of what you appended? Eg if you have `sb.Append("abc"); sb.Append("xyz")`, do you want `"xyzabc"` or `"zyxcba"`? – James Thorpe Dec 22 '17 at 15:31
  • @JamesThorpe I'm trying to return "01101" to "10110" – springathing Dec 22 '17 at 15:37

2 Answers2

10

You have to turn it into a string, then reverse it, turn it into an array, then create a new string from that:

return new string(sb.ToString().Reverse().ToArray());
itsme86
  • 19,266
  • 4
  • 41
  • 57
4

We can write an extension method that follows the pattern used with other methods present in the StringBuilder class.
I mean, we can do the reverse directly on the StringBuilder buffer.

public static void Reverse(this StringBuilder sb)
{
    char t;
    int end = sb.Length - 1;
    int start = 0;
    
    while (end - start > 0)
    {
        t = sb[end];
        sb[end] = sb[start];
        sb[start] = t;
        start++;
        end--;
    }
}

Now we can use the extension with just one line of code

StringBuilder sb = new StringBuilder();
sb.Append("Testing reverse directly on the stringbuilder buffer");
sb.Reverse();
Console.WriteLine(sb.ToString());

Warning, this is just an exercise in answering the question posted. I don't know if it is more efficient or if there are drawbacks in this approach.
For sure, there is no new memory allocation required to store strings and array like in the canonical method. And given the fact that the user has already a stringbuilder in place I suppose that this approach could be used easily.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    Note that this avoids allocations but in exchange is more CPU expensive because of the indexer of `StringBuilder` -> might depend a lot on the use case and priorities – derHugo Jul 26 '23 at 07:56