嘿所有我新的F#F#查找字符串的指标在字符数组
我试图找到一个字符数组字符串的所有出现的起始索引。
例如 char array ['a';'b';'b';'a';'b';'b';'b';'b';'b';'a';'b']
将返回0和3和9,如果你正在寻找字符串“AB”
嘿所有我新的F#F#查找字符串的指标在字符数组
我试图找到一个字符数组字符串的所有出现的起始索引。
例如 char array ['a';'b';'b';'a';'b';'b';'b';'b';'b';'a';'b']
将返回0和3和9,如果你正在寻找字符串“AB”
下面是一个使用递归功能的解决方案:
/// Wraps the recursive findMatches function defined inside, so that you don't have to seed it with the "internal" paramters
let findMatches chars str =
/// Returns whether or not the string matches the beginning of the character array
let rec isStartMatch chars (str: string) =
match chars with
| char :: rest when str.Length > 0 ->
char = str.[0] && (isStartMatch rest str.[1..(str.Length - 1)])
| _ -> str.Length = 0
/// The actual function here
let rec findMatches matchedIndices i chars str =
match chars with
| _ :: rest ->
if isStartMatch chars str
then findMatches (i :: matchedIndices) (i + 1) rest str
else findMatches matchedIndices (i + 1) rest str
| [] -> matchedIndices
findMatches [] 0 chars str
不是最有效的,因为它遍历字符两次,如果他们是比赛的一部分,但是这不是一个真正的心腹大患。
我不想在这里做一个完整的例子,所以这里是提示:
let rec match (l:char seq) i=
match seq.tryFindindex ... (*the part you have already done goes here*)with
|None -> []
|Some(t) ->i+t::(match (Seq.skip t l) (i+t)
基本上,我们只是重复应用Findindex
,直到它停止匹配。
让我找到(l:char seq)i = match Seq.tryFindIndex(fun a - > String.Compare(a,searchSeq)= 0)with | None - > [] | Some ) - > i + t::(找到(Seq.skip tl)(i + t)) 它说没有不是一个int是真的。我如何允许这个结果? – TJF
你能证明你卡在哪里吗? –
我试过使用List.FindIndex,但只返回第一个索引 – TJF
它是否应该返回9? – Rodion