Search code examples
clojure

How to create a "replace-second" function in Clojure?


(clojure.string/replace-first "a x x c d" #"x" "b" )) ; Replace first

what if I want to replace the second x in the above string?


Solution

  • Hmm maybe you can compromise?

    (-> "a x x c d"  
      (clojure.string/replace-first #"x" "_")
      (clojure.string/replace-first #"x" "b" )
      (clojure.string/replace-first #"_" "x"))
    

    Just make sure _ can't be in the string.

    :)