Videos
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());
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.
I'm coming from Java, where I'm used to being able to tackle string-reversing problems with something as quick as this:
String palindrome = "level"; StringBuffer buffer = new StringBuffer(palindrome); return buffer.reverse();
I've spent the past few hours studying the documentation of C# and looking for an equivalent, but StringBuilders don't seem to scratch this itch. The most I've found is reversing an array. This seems useful, but since I sometimes like to reverse a string to solve numerical problems (convert an int to a string, reverse the string, return the reversed int), it'd be handy to not have to rely on this.
Since I'm studying the topic, I thought I should at least ask now, am I essentially on the right track? Or is there something obvious that I might be missing?