例如,假设我有一个列表
'("The" " " "Brown" " " "Cow")
Run Code Online (Sandbox Code Playgroud)
我想把它变成
"The Brown Cow"
Run Code Online (Sandbox Code Playgroud)
在clojure中有一个命令可以做到这一点吗?
lee*_*ski 16
我宁愿用apply它:
(apply str '("The" " " "Brown" " " "Cow"))
Run Code Online (Sandbox Code Playgroud)
由于它只调用一次函数,因此对于大型集合来说效率更高:
(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
Run Code Online (Sandbox Code Playgroud)
正如克里斯提到的,你可以使用clojure.string/join
另一种不使用库的方法(假设您不需要任何空格。)是:
(reduce str '("The" " " "Brown" " " "Cow"))
Run Code Online (Sandbox Code Playgroud)
将返回
"The Brown Cow"
Run Code Online (Sandbox Code Playgroud)
str获取一系列事物并将它们转换为一个字符串。你甚至可以这样做:(str "this is a message with numbers " 2 " inside")
| 归档时间: |
|
| 查看次数: |
2568 次 |
| 最近记录: |