Home > database >  I want to create from a string separated by commas (i.e. `,`) into a new string
I want to create from a string separated by commas (i.e. `,`) into a new string

Time:01-25

I want to create from a string separated by , into a new formated string:

Example "ice cream,orange juice" -> "say 1 for ice cream, say 2 for juice"

CodePudding user response:

Since you didn't provide details of what you're trying to achieve, what you've tried, and how general you want the solution to be, here's a somewhat minimal answer.

user> (require '[clojure.string :as str])
nil
user> (def ex "ice cream,orange juice")
#'user/ex
user> (def s (str/split ex #","))
#'user/s
user> (println (pr-str (format "say 1 for %s, say 2 for %s" (get s 0) (get s 1))))
"say 1 for ice cream, say 2 for orange juice"
nil
user> 

The above does not handle the case where you might want to skip escaped commas in the input (as in CSV files). It also just works for an input string with just one comma in it.

CodePudding user response:

General solution with map-indexed:

(->> (clojure.string/split "ice cream,orange juice" #",")
     (map-indexed #(str "say " (inc %1) " for " %2))
     (clojure.string/join ", "))

=> "say 1 for ice cream, say 2 for orange juice"

Solution with iterate:

(->> (clojure.string/split "ice cream,orange juice" #",")
     (map #(str "say " %1 " for " %2)
          (iterate inc 1))
     (clojure.string/join ", "))

=> "say 1 for ice cream, say 2 for orange juice"

Where:

  • ->> is thread-last macro
  • iterate creates increasing indices
  • map called with two collections joins index and one word from splitted string into one string
  • clojure.string/join joins these strings together with given separator

EDIT: One more solution with cl-format:

(clojure.pprint/cl-format nil "~{say ~a for ~a~^, ~}"
  (interleave (iterate inc 1)
              (clojure.string/split "ice cream,orange juice" #",")))

=> "say 1 for ice cream, say 2 for orange juice"
  •  Tags:  
  • Related