Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove characters from string in f#

Tags:

string

replace

f#

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?

like image 657
deostroll Avatar asked Dec 08 '22 11:12

deostroll


1 Answers

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
like image 124
p.s.w.g Avatar answered Dec 11 '22 01:12

p.s.w.g