例如我有(list "a" "1" "b" "2" "c" "3")
.
现在我想把这个列表变成一个"a1b2c3"
。
我怎么做?
谢谢你。
例如我有(list "a" "1" "b" "2" "c" "3")
.
现在我想把这个列表变成一个"a1b2c3"
。
我怎么做?
谢谢你。
(apply string-append (list "a" "1" "b" "2" "c" "3"))
或者(string-append* "" (list "a" "1" "b" "2" "c" "3"))
应该工作。请参阅:http ://docs.racket-lang.org/reference/strings.html
如果你想要一个程序来做到这一点,你可以写(define (strings->string sts) (apply string-append sts))
不要重新发明轮子!在 Racket 中,有一个专门为此而设计的程序,它被称为string-join
:
(string-join '("a" "1" "b" "2" "c" "3") "")
=> "a1b2c3"
引用文档:
(string-join strs
[sep
#:before-first before-first
#:before-last before-last
#:after-last after-last]) → string?
strs : (listof string?)
sep : string? = " "
before-first : string? = ""
before-last : string? = sep
after-last : string? = ""
在 中追加字符串,在 strs 中的每对字符串之间
strs
插入。, , 和类似于 的输入:它们分别指定最后两个字符串、前缀字符串和后缀字符串之间的备用分隔符。sep
before-last
before-first
after-last
add-between
值得一提的是,这里有一些带有和不带分隔符的实现(即插入在每对字符串之间的字符串,例如空格或逗号)。
函数fold
和fold-right
来自 SRFI 1。
连接非常多或非常长的字符串时,使用字符串端口可能会更快。否则不太可能有太大的速度差异。
(define (string-join strings)
(fold-right string-append "" strings))
(define (string-join strings)
(let loop ((strings strings) (so-far ""))
(if (null? strings)
so-far
(loop (cdr strings) (string-append so-far (car strings))))))
(define (string-join strings)
(parameterize ((current-output-port (open-output-string)))
(for-each write-string strings)
(get-output-string (current-output-port))))
(define (string-join strings delimiter)
(if (null? strings)
""
(fold (lambda (s so-far) (string-append so-far delimiter s))
(car strings)
(cdr strings))))
(define (string-join strings delimiter)
(if (null? strings)
""
(let loop ((strings (cdr strings)) (so-far (car strings)))
(if (null? strings)
so-far
(loop (cdr strings)
(string-append so-far delimiter (car strings)))))))
(define (string-join strings delimiter)
(if (null? strings)
""
(parameterize ((current-output-port (open-output-string)))
(write-string (car strings))
(for-each (lambda (s)
(write-string delimiter)
(write-string s))
(cdr strings))
(get-output-string (current-output-port)))))