F#删除/替换特定字符串索引

时间:2016-11-12 14:58:16

标签: string replace f#

我想删除字符串中的字符。但不是字符串中该字符的所有元素。例。我希望"|red|red|red|red|"变成"red|red|red|red"所以我想创建一个函数来检查字符串的第一个和最后一个索引是否是某个字符串,如果是这样的话就将其删除。

到目前为止,我想出了类似的东西:

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 

任何人都可以帮我弄清楚我能在函数中写些什么吗?当然,如果您发现更加方便,也欢迎您提出完全不同的功能。

提前谢谢!

2 个答案:

答案 0 :(得分:4)

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

用法:

replace '|' "|red|red|red|red|"

// val it : string = "red|red|red|red"

这是一个使用字符串而不是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

<强>更新

正如马克建议更好的选择是重新使用Trim

let replace (elem:string) (str:string) = str.Trim(elem.ToCharArray())

答案 1 :(得分:0)

我最终没有使用Gutavo的修复,但正是他激励我修复自己的功能!

let rec theButcher (s : string) : string =
    match s.[0] with
    |'|'|','|'.'|'-'|' ' -> (theButcher s.[1..])
    |_ -> match s.[(String.length s)-1] with
          |'|'|','|'.'|'-'|' ' ->  (theButcher s.[0..((String.length s)-2)])
          |_ -> s