String Haskell在字符串中查找字符串的索引
我目前正在尝试在另一个字符串中查找特定字符串的索引。 例如,在String Haskell在字符串中查找字符串的索引,string,haskell,find,substring,String,Haskell,Find,Substring,我目前正在尝试在另一个字符串中查找特定字符串的索引。 例如,在“abababab bla ab”中,字符串“ab”的结果应该是11和18。 如果当前我的函数也有索引0和8的问题 我的职能: findSubstringIndices :: String -> String -> [Int] findSubstringIndices text pattern = map (add 1) (findIndices (pattern `isPrefixOf`) (tails text))
“abababab bla ab”
中,字符串“ab”
的结果应该是11和18。
如果当前我的函数也有索引0和8的问题我的职能:
findSubstringIndices :: String -> String -> [Int]
findSubstringIndices text pattern = map (add 1) (findIndices (pattern `isPrefixOf`) (tails text))
选择合适的设备在这里很重要
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")]
例如:
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")]
现在,编写函数findsubstringindice
几乎变得微不足道:
findSubstringIndices :: String -> String -> [Int]
findSubstringIndices text pattern = [i | (i, w) <- words' text, w == pattern]
但是,这会以相反的顺序返回索引
g>let str = "ababa baab ab bla ab"
str :: [Char]
g>findWordIndices' "ab" str
[18,11]
it :: [Int]
这可以通过使用(++)
而不是cons((:)
)来解决
单词的另一种变体
:
import Data.Char
import Control.Arrow
words' s =
case dropWhile isSpace' s of
[] -> []
s' -> ((head >>> snd) &&& map fst) w : words' s''
where (w, s'') = break isSpace' s'
where isSpace' = fst >>> isSpace
indices text pattern =
map fst $ filter (snd >>> ((==) pattern)) $ words' $ zip text [0..]
main = do
putStrLn $ show $ indices "ababa baab ab bla ab" "ab"
根据您的说明,您应该得到的第一个索引是0。@larsmanns您是对的,我编辑了我的问题,所以您实际上是在寻找字符串“ab”,而不是“ab”。注意空格,也可以得到2。我猜你对单词提取感兴趣?请相应地重写问题,并给出输入和期望输出的示例。
import Data.Char
import Control.Arrow
words' s =
case dropWhile isSpace' s of
[] -> []
s' -> ((head >>> snd) &&& map fst) w : words' s''
where (w, s'') = break isSpace' s'
where isSpace' = fst >>> isSpace
indices text pattern =
map fst $ filter (snd >>> ((==) pattern)) $ words' $ zip text [0..]
main = do
putStrLn $ show $ indices "ababa baab ab bla ab" "ab"