在Racket中测试字符串中是否存在子字符串

时间:2019-11-03 17:41:35

标签: string substring racket

测试Racket中的字符串中是否存在子字符串。

我的代码如下所示。

(define (check-for-substring/list loc loc-to-find)
  (cond [(empty? loc-to-find) true]
        [(empty? loc) false]
        [(char=? (first loc) (first loc-to-find))
         (or (check-for-substring/list (rest loc) (rest loc-to-find))
             (check-for-substring/list (rest loc) loc-to-find))]
        [else (check-for-substring/list (rest loc) loc-to-find)]))

(define (check-for-substring string substring)
  (check-for-substring/list (string->list string) (string->list substring)))

测试示例如下所示。

(check-expect (check-for-substring "flag" "flagged") false)
(check-expect (check-for-substring "flagged" "flag") true)
(check-expect (check-for-substring "" "") true)
(check-expect (check-for-substring "a" "") true)

不适用于我的代码的测试示例:

(check-expect (check-for-substring "flaminegio" "flamingo") false)
(check-expect (check-for-substring "heiloght" "height") false)

注意:对于那些不熟悉使用“列表缩写”的学生的语言,没有“本地”函数允许在函数中定义函数,并且使用“列表”代替“ cons”。同样,“长度”功能输出列表的长度,而不是字符串的长度。您可以在评论中要求更多的说明。

1 个答案:

答案 0 :(得分:0)

每次找不到时,都需要“重置”子字符串,否则最终""将与整个字符串匹配,这当然总是返回true

一种简单的方法是将问题分成两个“循环”,一个循环遍历整个字符串,另一个循环检查子字符串的一次出现,从整个字符串的当前位置开始。试试这个:

(define (check-for-substring string substring)
  (check-for-substring/list (string->list string) (string->list substring)))

(define (check-for-substring/list loc loc-to-find)
  (cond [(empty? loc-to-find) true]
        [(empty? loc) false]
        [(check-one loc loc-to-find) true]
        [else (check-for-substring/list (rest loc) loc-to-find)]))

(define (check-one loc loc-to-find)
  (cond [(empty? loc-to-find) true]
        [(empty? loc) false]
        [(not (char=? (first loc) (first loc-to-find))) false]
        [else (check-one (rest loc) (rest loc-to-find))]))

它按预期工作:

(check-for-substring "flag" "flagged")
=> #f

(check-for-substring "flagged" "flag")
=> #t

(check-for-substring "" "")
=> #t

(check-for-substring "a" "")
=> #t

(check-for-substring "flaminegio" "flamingo")
=> #f

(check-for-substring "heiloght" "height")
=> #f