在clojure中将字符串列表转换为单个字符串

时间:2016-03-09 06:12:16

标签: clojure

例如,假设我有一个列表

'("The" " " "Brown" " " "Cow")

我想把它变成

"The Brown Cow" 

clojure中是否有命令执行此操作?

3 个答案:

答案 0 :(得分:14)

我宁愿使用apply

(apply str '("The" " " "Brown" " " "Cow"))

由于它只调用一次函数,因此对大型集合来说效率更高:

(defn join-reduce [strings] (reduce str strings))
(defn join-apply [strings] (apply str strings))

user> (time (do (join-reduce (repeat 50000 "hello"))
                nil))
"Elapsed time: 4708.637673 msecs"
nil
user> (time (do (join-apply (repeat 50000 "hello"))
                nil))
"Elapsed time: 2.281443 msecs"
nil

答案 1 :(得分:-2)

请人们,只是说'不''到列表!矢量这么简单:

(ns clj.demo
  (:require [clojure.string :as str] ))

(def xx [ "The"  " "  "Brown"  " " "Cow" ] )
(prn (str/join xx))
;=> "The Brown Cow"

引用列表如:

'( "The"  " "  "Brown"  " " "Cow" )

比单纯的矢量文字更难打字和阅读,而且更容易出错:

 [ "The"  " "  "Brown"  " " "Cow" ]

答案 2 :(得分:-3)

正如克里斯提到的,你可以使用clojure.string/join

不使用库的另一种方法(假设你不需要任何空格。)是:

(reduce str '("The" " " "Brown" " " "Cow"))

将返回

"The Brown Cow"

str获取一系列内容并将其转换为一个字符串。你甚至可以这样做:(str "this is a message with numbers " 2 " inside")