user10601169
user10601169

Reputation:

Initialize list from string?

I have the string "H1E1T1H1" for which I want to replace each '1' with a string such as "OP" and I think that this would be easiest accomplished using lists because of the ease of adding elements. However, I wonder how I can initialize a list from a sting? (if using lists actually does not make it much easier, please correct me :) )

Upvotes: 0

Views: 73

Answers (1)

Szer
Szer

Reputation: 3476

The easiest way (and it is idiomatic in F#) is to use String.Replace method as follow:

let str = "H1E1T1H1"
let result = str.Replace("1","OP")

But in case you want FP just because you can... :)

"H1E1T1H1"
|> Seq.map (function | '1' -> "OP" | x -> string x)
|> String.concat ""

In case you wanted to replace the same character with different strings according to the character's index

"H1E1T1H1"
|> Seq.mapi (fun i x ->
    match i,x with
    | (i, '1') when i < 4 || i > 6 -> "OP"
    | (_, x) -> string x)
|> String.concat ""

Upvotes: 2

Related Questions