子串指标

Roz*_*uur 2 f# substring

我是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|]
Run Code Online (Sandbox Code Playgroud)

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

des*_*sco 5

就像是

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        
        )
Run Code Online (Sandbox Code Playgroud)