如何在方案中将字符串列表转换为一个字符串?

时间:2013-06-02 07:06:08

标签: string list scheme racket intermediate-language

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

现在我想将此列表转换为一个"a1b2c3"

我该怎么做?

谢谢。

3 个答案:

答案 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"

引用documentation

(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-last类似于add-between的输入:它们分别指定最后两个字符串,前缀字符串和后缀字符串之间的备用分隔符

答案 2 :(得分:1)

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

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