More efficient than using seq functions:
(defn str-insert "Insert c in string s at index i." [sci] (str (subs s 0 i) c (subs si)))
In REPL:
user=> (str-insert "aple" "p" 1) "apple"
NB. This function does not really care about type c or its length in the case of a string; (str-insert "aple" \p 1) and (str-insert "ale" "pp" 1) also (in general, (str c) , that is, an empty string if c is nil and (.toString c) otherwise).
Since the question asks for the idiomatic way of doing the task at hand, I also note that I consider it preferable (in terms of “semantic fit” in addition to performance advantages) to use string functions when working with specific strings; this includes subs and functions from clojure.string . See design notes at the top of clojure.string for a discussion of idiomatic string handling.
Michał Marczyk
source share