繁体   English   中英

检查字符串是否包含给定的子字符串并返回 BOOLEAN [重复]

[英]Check a string if it contains a given substring and return BOOLEAN [duplicate]

我正在尝试提出一个带有 2 个字符串参数的 haskell 函数。 然后它检查第一个字符串是否包含第二个字符串作为子字符串。 例如:“bring”包含子字符串“in”。 如果传递“bring”“in”,函数应该返回true。 这是我到目前为止所拥有的,但它并没有真正起作用。 部分工作。 我不知道如何在递归情况下分配真值。

check::[Char]->[Char]->Bool
check [][]              =False
check _[]               =False
check []_               =False
check(x:xs)(y:ys)
 | y==x                 =True
 | otherwise            =check xs (y:ys)

main = do
print $ check "bring" "in"

一个完全不使用库或酷技巧的直接实现可能是:

substring :: String -> String -> Bool
substring (_:_) [] = False
substring xs ys
    | prefix xs ys = True
    | substring xs (tail ys) = True
    | otherwise = False

prefix :: String -> String -> Bool
prefix [] _ = True
prefix (_:_) [] = False
prefix (x:xs) (y:ys) = (x == y) && prefix xs ys

这是天真的子字符串搜索的“规范”方式(我猜是在任何编程语言中?):对于字符串的每个后缀,您检查子字符串是否是前缀。

请注意,子字符串参数在字符串之前。

它不起作用的原因是因为您似乎只匹配第二个字符串的第一个字符:

check::[Char]->[Char]->Bool
check [][]              =False
check _[]               =False
check []_               =False
check(x:xs)(y:ys)
 | y == x               =True -- this line
 | otherwise            =check xs (y:ys)

main = do
print $ check "bring" "in"

通过执行以下操作修复它:

check::[Char]->[Char]->Bool
check l s = check' l s True where
    check' _ [] h          = True
    check' [] _ h          = False
    check' (x:xs) (y:ys) h = (y == x && check' xs ys False) || (h && check' xs (y:ys) h)

main = do
print $ check "bring" "in"

另请注意,如前所述,空字符串是其自身和任何非空字符串的子集。 额外的布尔值是快速消除当前搜索并再次从子字符串开始

最后,要成为一名优秀的程序员,我们可以通过以下方式使其通用:

check::Eq a => [a]->[a]->Bool
check l s = check' l s True where
    check' _ [] h          = True
    check' [] _ h          = False
    check' (x:xs) (y:ys) h = (y == x && check' xs ys False) || (h && check' xs (y:ys) h)

main = do
print $ check "bring" "in"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM