我需要一个函数来查找字符串中子字符串的所有索引。您可以在下面找到我的代码,但我只是想知道是否有更好的方法:
-- find index of substring in string
-- index_of_substring "so" "unsomesome" -> Just 2
-- index_of_substring "to" "unsomesome" -> Nothing
index_of_substring :: String -> String -> Maybe Int
index_of_substring _ [] = Nothing
index_of_substring sub str = case List.isPrefixOf sub str of
False -> fmap (+1) $ index_of_substring sub (tail str)
True -> Just 0
-- find all occurences of pattern in a string
-- all_occurrences_of_pattern_in_string "so" "unsomesomesome" -> [2,6,10]
all_occurrences_of_pattern_in_string pattern s = helper pattern s [] 0
where helper pattern s result last_idx = case index_of_substring pattern s of
Just n -> helper pattern (drop (n + 1) s) (result ++ [n + last_idx]) (last_idx + n + 1)
Nothing -> result