答案 0 :(得分:2)
这看起来像是interleave
的工作。一旦你弄清楚如何实现它(请参阅链接的答案以获取更多详细信息),您的程序将很容易编写:
(define (alternate-string str1 str2)
(list->string
(interleave (string->list str1)
(string->list str2))))
当然,它会按预期工作:
(alternate-string "tom" "hey")
=> "thoemy"
答案 1 :(得分:1)
你在这里有很多选择。
最简单的可能是经典的名为let :
使用列表
(define (alternate-string s1 s2)
(let loop ((l1 (string->list s1)) (l2 (string->list s2)) (res '()))
(if (or (null? l1) (null? l2))
(list->string (reverse res))
(loop (cdr l1) (cdr l2) (cons (car l2) (cons (car l1) res))))))
使用字符串追加
(define (alternate-string s1 s2)
(let loop ((l1 (string->list s1)) (l2 (string->list s2)) (res ""))
(if (or (null? l1) (null? l2))
res
(loop (cdr l1) (cdr l2) (string-append res (string (car l1) (car l2)))))))
但你也可以使用R6RS内置弃左:
(define (alternate-string s1 s2)
(fold-left
(lambda (r e1 e2) (string-append r (string e1 e2)))
""
(string->list s1) (string->list s2)))
或者,如果 Racket 语法是一个选项:
(define (alternate-string s1 s2)
(for/fold ((res "")) ((c1 s1) (c2 s2))
(string-append res (string c1 c2))))
答案 2 :(得分:0)
您需要转换为列表吗?您可以通过使用string-ref
和string-set!
直接操作字符串来逐步操作字符串并逐个插入字符:
(define (alternate string1 string2)
(assert (= (string-length string1) (string-length string2))
(let ((result (make-string (* 2 (string-length string1)))))
(let filling ((n 0))
(when (< n (string-length string1))
(string-set! result (+ (* 2 n) 0) (string-ref string1 n))
(string-set! result (+ (* 2 n) 1) (string-ref string2 n))
(filling (+ n 1))))
result)))
> (alternate "abc" "123")
"a1b2c3"
请注意,filling
过程是递归的,尾递归,并正确终止。