我对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|]
我不想找一个解决方案,检查每个索引的子串匹配。
BTW,没有必要做'在这个例子中indices'可变的。这种集合类型本身是可变的。通过声明'indices'可变,你可以创建一个可变引用到可变集合。 – wmeyer 2011-03-02 19:17:37