StringBuilder

Reverse String
Reverse String in F#
module ReverseString

open System.Text

let reverse (input: string) =
    let chars = StringBuilder()
    for char in Seq.rev input do
        chars.Append(char) |> ignore
    chars.ToString()

Strings can also be created using the StringBuilder class. The purpose of this class is to efficiently and incrementally build a string.

Note

A StringBuilder is often overkill when used to create short strings, but can be very useful to create larger strings.

The first step is to create a StringBuilder. We then use a for-loop to walk through the string's characters in reverse order via the Seq.rev function, appending them to the StringBuilder via its Append() method.

Finally, we return the reversed string by calling the ToString() method on the StringBuilder instance.

30th Oct 2024 · Found it useful?