【问题标题】:Flexible replace substring - Scheme灵活的替换子串 - 方案
【发布时间】:2015-08-31 02:55:42
【问题描述】:

在Scheme中,有没有一种用另一个字符串替换一个字符串的子字符串的好方法,它的长度可能会有所不同?我正在寻找类似的东西:

(replace-all string pattern replacement)
(replace-all "slig slog slag" "g" "ggish")
    => "sliggish sloggish slaggish"

【问题讨论】:

    标签: string replace scheme substring


    【解决方案1】:

    您可以自己动手。它不是很有效,但它会在小字符串上完成工作。 (我不会在超过一百万个字符的字符串长度上使用它)

    如果列表的开头srcprefix 相同,则使(prefix? src prefix) 计算为#t。

    使(append-reverse rev-head tail) 使得(append-reverse '(1 2 3) '(4 5 6)) ; ==> (3 2 1 4 5 6)。这可以通过foldl 轻松完成,或者这是SRFI-1 中的标准程序

    那么(replace-all haystack needle replacement)就很简单了:

    (define (replace-all haystack needle replacement)    
      ;; most of the processing works on lists 
      ;; of char, not strings.
      (let ((haystack (string->list haystack))
            (needle (string->list needle))
            (replacement (string->list replacement))
            (needle-len (string-length needle)))
        (let loop ((haystack haystack) (acc '()))
          (cond ((null? haystack)
                 (list->string (reverse acc)))
                ((prefix? haystack needle)
                 (loop (list-tail haystack needle-len)
                       (reverse-append replacement acc)))
                (else
                 (loop (cdr haystack) (cons (car haystack) acc)))))))
    
    (replace-all "The cat looks like a cat." "cat" "dog")
    ; ==> "The dog looks like a dog."
    

    【讨论】:

      【解决方案2】:

      当然,请查看您的 Scheme 解释器的文档以找到合适的过程。例如,在 Racket 中,我们有 string-replace,其工作方式如下:

      (string-replace "slig slog slag" "g" "ggish")
      => "sliggish sloggish slaggish"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 2015-10-12
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多