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?
Since no one has posted this yet, the Core.String
module contains the methods you're looking for.
To replace the given characters with a space (or any other given single character), use String.map
:
let strip chars = String.map (fun c -> if Seq.exists((=)c) chars then ' ' else c)
strip "xyz" "123x4y5z789" // 123 4 5 789
To remove the given characters entirely, use String.collect
:
let strip chars = String.collect (fun c -> if Seq.exists((=)c) chars then "" else string c)
strip "xyz" "123x4y5z789" // 12345789
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With