如何替换给定索引处的字符串元素

时间:2015-06-03 16:36:59

标签: f#

string s = "foo.bar"
s[s.LastIndexOf(".")] = "-"

在类似c语言中听起来很简单,但在F#中让我疯狂。

我的代码:

let sb = new StringBuilder(s)
sb.[s.LastIndexOf(".")] <- '-'
let s = sb.ToString()

有更优雅的方法吗?就像使用|>一样?我不想明确声明一个新变量sb

4 个答案:

答案 0 :(得分:3)

或者,您可以按照以下方式执行此操作:

let s = "foo.bar"
let index = s.LastIndexOf('.')
let s1 = s |> String.mapi(fun i x -> if i=index then '-' else x)
s1 |> printfn "%A"

打印:“foo-bar”

链接:https://dotnetfiddle.net/5FjFR1

答案 1 :(得分:2)

您可以直接使用char array,而不是使用StringBuilder包裹。

let replaceAt i c (s: string) = 
    let arr = s.ToCharArray()
    arr.[i] <- c
    String arr

"foo.bar" |> replaceAt 3 '-'

有些测试使用mapi -

将其与this one进行比较
let replaceAt2 index x s = s |> String.mapi (fun i x -> if i=index then '-' else x)

let test f =
    let rec loop n =
        if n > 0 then
            let x = "foo.bar" |> f 3 '-'
            loop (n - 1)
    loop 10000000

test replaceAt  // Real: 00:00:01.188, CPU: 00:00:01.201, GC gen0: 168, gen1: 168, gen2: 0
test replaceAt2 // Real: 00:00:05.587, CPU: 00:00:05.584, GC gen0: 275, gen1: 275, gen2: 0

答案 2 :(得分:2)

这里已有很好的建议。这是另一种方法:

let s = "foo.bar"
let idx = s.LastIndexOf '.'
let replaced = s.Substring(0, idx) + "-" + s.Substring(idx + 1)

答案 3 :(得分:1)

为了它的乐趣,我尝试了一个&#34;更多&#34; List.foldBack的功能方法。请在.NET Fiddle处为自己尝试以下代码。

let replaceLastOf candidate replacement l = 
    let replaceAndPrepend x (xs, found) =
        if not found && x = candidate 
        then (replacement::xs, true)
        else (x::xs, found)
    fst <| List.foldBack replaceAndPrepend l ([], false)

let replaceLastCharOf candidate replacement (str:string) =
    List.ofSeq str
    |> replaceLastOf candidate replacement
    |> Array.ofList 
    |> System.String.Concat

<强>用法

printfn "%A" (replaceLastOf 1 9 [1;3;1;4;1])
printfn "%A" (replaceLastCharOf '.' '-' "f.oo.bar")

<强>输出

[1; 3; 1; 4; 9]
"f.oo-bar"