I want to remove a char in a string. but not all the elements of that char in a string. example. i want "|red|red|red|red|" to turn into "red|red|red|red" So I want to create a function that checks if the first and last index of a string is a certain char and remove it if its the case.
so far i have come up with something like this:
let rec inputFormatter (s : string) : string =
match s.[1] with
|'|'|','|'.'|'-' -> // something that replaces the char with "" in the string s
(inputFormatter s)
|_ -> match s.[(String.length s)] with
|"|"|","|"."|"-" -> // same as above.
(inputFormatter s)
|_ -> s
Can anyone help me figure out what i could write in my function? Ofcourse you are also welcome to come up with an etirely different function if you find that more conveniet.
thanks in advance!
let replace elem (str:string) =
let len = String.length str
if str.[0] = elem && str.[len-1] = elem then str.[1..len-2]
else str
Usage:
replace '|' "|red|red|red|red|"
// val it : string = "red|red|red|red"
And here's a version working with string instead of char:
let replace elem (str:string) =
let lens = String.length str
let lene = String.length elem
if lene <= lens && str.[0..lene-1] = elem && str.[lens-lene..lens-1] = elem then str.[lene..lens-lene-1]
else str
UPDATE
As Mark suggested a better option is re-using Trim
let replace (elem:string) (str:string) = str.Trim(elem.ToCharArray())
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