2014-02-14 3 views
1

Привет всем Я новичок в F #е # нахождение индексов строки в массив символов

Я пытаюсь найти начальные индексы всех вхождений строки в массив символов.

например. char array ['a'; 'b'; 'b'; 'a'; 'b'; 'b'; 'b'; 'b'; 'b'; 'a'; 'b']

будет возвращать 0 и 3 и 9, если вы ищете строку «AB»

+1

Можете ли вы показать, где вы застряли? –

+0

Я попытался использовать List.FindIndex, но это возвращает только первый индекс – TJF

+1

, если он вернет вас 9? – Rodion

ответ

2

Вот решение, используя рекурсивные функции:

/// 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 

не самым эффективным, как она перебирает символы дважды, если они являются частью матча, но это не очень большое беспокойство.

1

Я не хочу, чтобы сделать полный пример здесь, так вот подсказка:

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, пока он не перестанет соответствовать.

+0

let rec find (l: char seq) i = матч Seq.tryFindIndex (fun a -> String.Compare (a, searchSeq) = 0) с | None -> [] | Some (t) -> i + t: :(find (Seq.skip tl) (i + t)) В нем говорится, что ни один не является int, который является истинным. Как разрешить этот результат? – TJF

Смежные вопросы