挑選合適的設備在這裏很重要。
import Data.Char
你可以從你的序幕,這被定義爲使用該功能words
略加修改的版本:
words :: String -> [String]
words s = case dropWhile isSpace s of
"" -> []
s' -> w : words s'' where (w, s'') = break isSpace s'
它打破字符串成的空間分隔的單詞列表。修改將等於將每個單詞的索引標記到字符串中。例如:
words' :: String -> [(Int, String)]
words' = go 0
where
go n s = case break (not . isSpace) s of
(_, "") -> []
(ws, s') -> (n', w) : go (n' + length w) s''
where
n' = n + length ws
(w, s'') = break isSpace s'
例如:
> words' "ababa baab ab bla ab"
[(0,"ababa"),(6,"baab"),(11,"ab"),(14,"bla"),(18,"ab")]
現在,寫你的函數findSubstringIndices
變得幾乎微不足道:
findSubstringIndices :: String -> String -> [Int]
findSubstringIndices text pattern = [i | (i, w) <- words' text, w == pattern]
是否行得通?是的,它的作用:
> findSubstringIndices "ababa baab ab bla ab" "ab"
[11,18]
你應該得到的第一個索引,給您的規格,爲0 – 2012-07-11 12:21:14
@larsmanns你說得對,我編輯我的問題 – LeonS 2012-07-11 12:22:35
所以你實際上是尋找字符串「ab」,而不是「ab」。注意空間 – Squidly 2012-07-11 12:22:50