【问题标题】:Testing for the occurrence of a substring in a string in Racket测试 Racket 中字符串中子字符串的出现
【发布时间】:2020-02-29 03:31:51
【问题描述】:

在 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)

注意:对于那些不熟悉具有列表缩写的初学者语言的人,没有允许在函数中定义函数的“本地”函数,并且使用“列表”而不是“缺点”。此外,“length”函数输出列表的长度,而不是字符串的长度。您可以在 cmets 中要求更多说明。

【问题讨论】:

  • @tjorchrt 抱歉。只是你的代码不起作用。有一个奇怪的函数“take”。
  • 我已经提到了#lang racket。

标签: string substring racket


【解决方案1】:

每次您找不到匹配项时,您都需要“重置”子字符串,否则您最终会将"" 与完整字符串匹配,这当然总是会返回@ 987654322@.

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

(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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 2021-02-10
    • 2011-07-25
    • 2018-04-02
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多