This splits the string sequence into blocks, then joins all groups of strings which should be joined with a single string/join
call per group, so it avoids the quadratic behaviour of solutions pastings strings together one by one:
(def xs ["a" "b" " c" "d" " e" " f" "g"])
(require '[clojure.string :as string])
(->> xs
(partition-by #(.startsWith ^String % " "))
(map vec)
(partition-all 2)
(reduce (fn [acc [ps ss]]
(-> acc
(into (pop ps))
(conj (string/join "" (cons (peek ps) ss)))))
[]))
;= ["a" "b c" "d e f" "g"]
Note that this assumes that the first string does not start with a space. To do away with this assumption, you could prepend an empty string ((cons "" xs)
instead of xs
in the above, or (cons "")
as the first ->>
step) to "catch" them. In that case the result would either start with a string resulting from joining together the sequence-initial strings starting with spaces or an empty space if the sequence does not start with such strings, so you can check for the presence of ""
at the first position in the result and possibly filter it out.