gpt4 book ai didi

f# - 子串索引

转载 作者:行者123 更新时间:2023-12-02 06:42:49 25 4
gpt4 key购买 nike

我是 F# 的新手。我编写了一个函数,该函数返回目标中子字符串匹配项的索引数组,它类似于我在 C# 中的编写方式。

有没有更实用的方法来解决这个问题,是否可以在不使用任何可变变量的情况下解决?

let SubStringIndices (haystack:string) (needle:string) =
let mutable indices = System.Collections.Generic.List<int>()
let mutable index = haystack.IndexOf(needle)
while index >= 0 do
indices.Add(index)
index <- haystack.IndexOf(needle, index+1)
indices.ToArray()

printfn "%A" (SubStringIndices "abaabababaaab" "ab")
// prints [|0; 3; 5; 7; 11|]

我不是在寻找在每个索引处检查子字符串匹配的解决方案。

最佳答案

有点像

let SubStringIndices (haystack:string) (needle:string) = 
-1 |> Seq.unfold (fun n ->
let idx = haystack.IndexOf(needle, n + 1)
if idx <> -1 then Some(idx, idx) else None
)

关于f# - 子串索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5169091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com