using System.Linq;
public static class ReverseString
{
public static string Reverse(string input)
{
return new string(input.Reverse().ToArray());
}
}
The string class implements the IEnumerable<char> interface, which allows us to call LINQ's Reverse() extension method on it.
To convert the IEnumerable<char> returned by Reverse() back to a string, we first use ToArray() to convert it to a char[].
Finally, we return the reversed string by calling its constructor with the (reversed) char[].
Shortening
There are two things we can do to further shorten this method:
- Remove the curly braces by converting to an expression-bodied method
- Use a target-typed new expression to replace
new stringwith justnew(the compiler can figure out the type from the method's return type)
Using this, we end up with:
public static string Reverse(string input) => new(input.Reverse().ToArray());
Performance
If you're interested in how this approach's performance compares to other approaches, check the performance approach.
4th Sep 2024
·
Found it useful?