12

例如我有(list "a" "1" "b" "2" "c" "3").

现在我想把这个列表变成一个"a1b2c3"

我怎么做?

谢谢你。

4

3 回答 3

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))

于 2013-06-02T07:35:28.130 回答
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插入。, , 和类似于 的输入:它们分别指定最后两个字符串、前缀字符串和后缀字符串之间的备用分隔符。sepbefore-lastbefore-firstafter-lastadd-between

于 2013-06-02T13:03:10.760 回答
4

值得一提的是,这里有一些带有和不带分隔符的实现(即插入在每对字符串之间的字符串,例如空格或逗号)。

函数foldfold-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)))))
于 2019-04-18T08:22:52.230 回答