Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Idiomatic Way to Insert a Char in a String

I have a string in Clojure and a character I want to put in between the nth and (n+1)st character. For example: Lets say the string is "aple" and I want to insert another "p" between the "p" and the "l".

  (prn 
     (some-function "aple" "p" 1 2)) 

  ;; prints "apple" 
  ;; ie "aple" -> "ap" "p" "le" and the concatenated back together.

I'm finding this somewhat challenging, so I figure I am missing information about some useful function(s) Can someone please help me write the "some-function" above that takes a string, another string, a start position and an end position and inserts the second string into the first between the start position and the end position? Thanks in advance!

like image 754
David Williams Avatar asked May 16 '13 03:05

David Williams


1 Answers

More efficient than using seq functions:

(defn str-insert
  "Insert c in string s at index i."
  [s c i]
  (str (subs s 0 i) c (subs s i)))

From the REPL:

user=> (str-insert "aple" "p" 1)
"apple"

NB. This function doesn't actually care about the type of c, or its length in the case of a string; (str-insert "aple" \p 1) and (str-insert "ale" "pp" 1) work also (in general, (str c) will be used, which is the empty string if c is nil and (.toString c) otherwise).

Since the question asks for an idiomatic way to perform the task at hand, I will also note that I find it preferable (in terms of "semantic fit" in addition to the performance advantage) to use string-oriented functions when dealing with strings specifically; this includes subs and functions from clojure.string. See the design notes at the top of the source of clojure.string for a discussion of idiomatic string handling.

like image 79
Michał Marczyk Avatar answered Sep 27 '22 18:09

Michał Marczyk