我正在尝试附加两个字符串
列表但我不知道如何在两个单词之间添加空格。
(define (string-concat lst1 lst2)
(map string-append lst1 lst2)
)
(string-concat '("elementary") "(school))
然后结果为" elementaryschool"
如何在合并时添加空间? 我曾尝试使用lambda,但它不起作用,如
(map string-append (cdr (append* (map (lambda (x) list " " x)) lst1)) lst2)
答案 0 :(得分:2)
使用add-between
在字符串之间添加放置空格:
> (add-between '("This" "and" "that") " ")
'("This" " " "and" " " "that")
要在列表中追加字符串,请使用string-append*
> (string-append* '("This" " " "and" " " "that"))
"This and that"
您的功能变为:
(define (string-concat lst1 lst2)
(string-append* (add-between (append lst1 lst2) " ")))
其中append
用于将两个列表合并为一个。
答案 1 :(得分:1)
您可以在两个字符串之间添加一个空格,string-append
接受多个参数:
(string-append "hello" " " "world")
=> "hello world"
或者您可以使用string-join
:
(string-join '("hello" "world"))
=> "hello world"
现在,将其扩展为字符串列表:
(map (lambda (s1 s2) (string-append s1 " " s2))
'("a" "b" "c")
'("1" "2" "3"))
=> '("a 1" "b 2" "c 3")
(map (lambda (s1 s2) (string-join (list s1 s2)))
'("a" "b" "c")
'("1" "2" "3"))
=> '("a 1" "b 2" "c 3")
答案 2 :(得分:1)
您可以使用match
执行此操作的另一种方法#lang racket
(define (add-between sep xs)
(match xs
;; at least two items
((list a b rest ...)
(string-append a sep (add-between sep (cons b rest))))
;; one item
((list a)
a)
;; no items
(null "")))
(add-between "~" '()) ;; ""
(add-between "~" '("a")) ;; "a"
(add-between "~" '("a" "b")) ;; "a~b"
(add-between "~" '("a" "b" "c")) ;; "a~b~c"
(add-between "~" '("a" "b" "c" "d")) ;; "a~b~c~d"
答案 3 :(得分:0)
如果要追加多个字符串,请不要使用string-append。
使用with-output-to-string
#lang racket
(define (string-concat lst1 lst2)
(with-output-to-string
(lambda ()
(map
(lambda (item1)
(printf "~a " item1))
lst1)
(map
(lambda (item2)
(printf "~a " item2))
lst2))))
(string-concat '("cat" "kitten") '("dog" "puppy"))
结果:
"cat kitten dog puppy "