Search code examples
clojure

How to replace a character in a string using index in clojure


I want to replace a character in a string using index. How to do that? Or is there any other way of accessing it?


Solution

  • Like almost everything commonly used in Clojure, strings are immutable, so you need to create a new string with the new character in place of the old at the desired location:

    (defn replace-at [s idx replacement]
      (str (subs s 0 idx) replacement (subs s (inc idx))))
    
    > (replace-at "012345" 2 "x")
    01x345