如何在clojure中将字符串拆分为固定数量的字符?

ris*_*ant 3 string split clojure

我是clojure的新手.我正在学习以各种方式分割字符串.我从这里得到帮助:https: //clojuredocs.org/clojure.string/split 没有示例将字符串拆分为固定数量的字符.

让一个字符串"大家欢迎大家来这里".我想在每个第4个字符后分割这个字符串,所以输出(分割后)应该是["hell""o ev""eryo""ne w""elco""me t""o he""re"].请注意,空格被视为char.

任何人都可以告诉我,我该怎么做?谢谢.

lee*_*ski 8

你可以使用re-seq:

user> (def s "hello everyone welcome to here")
#'user/s

user> (re-seq #".{1,4}" s)
("hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re")
Run Code Online (Sandbox Code Playgroud)

或者对字符串进行分区,将其视为seq:

user> (map (partial apply str) (partition-all 4 s))
("hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re")
Run Code Online (Sandbox Code Playgroud)

  • `(require '[clojure.string :as str])` 并使用 [`str/join`](https://clojuredocs.org/clojure.string/join) 而不是 `(partial apply str )`。 (2认同)

Mic*_*ent 5

带传感器:

(def sample "hello everyone welcome to here")

(into [] (comp (partition-all 4) (map #(apply str %))) sample)
Run Code Online (Sandbox Code Playgroud)

不过比其他例子慢:)。