例如我有(list "a" "1" "b" "2" "c" "3")
。
现在我想将此列表转换为一个"a1b2c3"
。
我该怎么做?
谢谢。
答案 0 :(得分:12)
(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))
答案 1 :(得分:9)
不要重新发明轮子!在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
的输入:它们分别指定最后两个字符串,前缀字符串和后缀字符串之间的备用分隔符
答案 2 :(得分:1)
对于它的价值,这里有一些带有或不带有分隔符的实现(即,在每对字符串之间插入一个字符串,例如空格或逗号)。
功能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)))))