remove characters from string in f#

f#, replace, string

Solution

As F# belongs to .NET stack we may rely upon the power of platform libraries. Then this character stripping task can be achieved as simple as

`open System open System.Linq let stripChars chars (text:string) = String.Concat(text.Except(stripChars))`

UPDATE: Unfortunately, later on I've realized that Enumerable.Except method produces the set difference of two sequences, meaning `stripChars "a" "ababab"` would be just `"b"` instead of expected `"bbb"`.

Continuing in LINQ venue the correctly working implementation may be more wordy:

let stripv1 (stripChars: seq<char>) (text:string) =
    text.Where(fun (c: char) -> not(stripChars.Contains(c))) |> String.Concat    

which probably do not worth effort compared with equivalent idiomatic F#:

let stripv2 (stripChars: seq<char>) text =
    text |> Seq.filter(fun c -> not (stripChars.Contains c)) |> String.Concat

So, a pure .NET-specific approach would be to follow Ruben's advice regarding `String.Split`from the comment below:

let stripv3 (stripChars:string) (text:string) =
    text.Split(stripChars.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) |> String.Concat

Problem

I have a `List<char>` in `stripchars`. These characters should not be present in string `text`. So I've made that mutable. So I do something like: ``` stripchars |> Seq.iter( fun x -> text <- text.Replace(x, ' ') ) ``` Then I get an error saying text is a mutable variable used in an invalid way. Now I go and look at this post, and I come out with something like ``` let s = ref text stripchars |> Seq.iter( fun ch -> printfn "ch: %c" ch printfn "resultant: %s" !s s := (!s).Replace(ch, ' ') ) ``` This still doesn't accomplish mutating the state of `text`. What is the correct way?

Original source

Related problems