Clojure: Idiomatic way to insert Char into a string

I have a line in Clojure and a character that I want to set between the nth and (n + 1) character. For example: Let's say the string is "aple" and I want to insert another "p" between "p" and "l".

(prn (some-function "aple" "p" 1 2)) ;; prints "apple" ;; ie "aple" -> "ap" "p" "le" and the concatenated back together. 

I find this somewhat complicated, so I believe that I lack information on any useful feature. Can someone please help me write "some function" above, which takes a line, another line, a start position and an end position and inserts the second line into the first between the start and end position? Thanks in advance!

+7
source share
1 answer

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.

+11
source

All Articles