开发者

replace spaces in string with comma

开发者 https://www.devze.com 2023-04-11 22:23 出处:网络
I need to take find all unique values from the below and pass them to a sql query.Below is an example of what I am trying to do, I am actually taking the data from a two files comapring them and getti

I need to take find all unique values from the below and pass them to a sql query. Below is an example of what I am trying to do, I am actually taking the data from a two files comapring them and getting the unique values.

My problem is that I want to put the values in a sql IN() clause but I am having trouble comma separating the values

I have tried using replace but that does not seem to work for me

(def snapshot 
                #{{:id "1234" :mtm "101" :pv"200"}
                {:id"1235" :mtm "101" :pv"200"}
                {:id"10234" :mtm "101" :pv"200"}
                {:id"12034" :mtm "101" :pv"200"}
                {:id"127" :mtm "101" :pv"200"}}
)
 (def snapshot1 
                #{{:id"1238" :mtm "104" :pv"200"}
                {:id"234" :mtm "101" :pv"200"}
                {:id"124" :mtm "101" :pv"200"}
                {:id"123" :mtm "101" :pv"200"}
                {:id"134" :mtm "101" :pv"200"}}
)
(def SNAPSHOT-IDsT (set (map :id snapshot)))

(def SNAPSHOT-IDsT1 (set (map :id snapshot1)))

(def id-in-one-file-only (difference SNAPSHOT-IDsT1 SNAPSHOT-IDsT))

(println id-in-one-file-only)

this gives me {1238 123 134 234 124}

How can I edit these results to give me {1238, 123, 134, 234, 124}

So that I can then pass it to a string

(str "Select * from table wh开发者_运维百科ere id in ("id-in-one-file-only")")

Any help or pointers with this would be much appreciated


difference returns a set, so I assume you have #{1238 123 134 234 124} as a result. How about a format fn:

user=> (defn format-ids [s]
         (str "{"
              (reduce #(str %1 ", " %2) s)
              "}"))

user=> (format-ids #{1238 123 134 234 124})
"{134, 234, 1238, 123, 124}"


interpose works nicely for this sort of thing:

user=> (apply str (interpose \, #{1238 123 134 234 124}))
"134,234,1238,123,124"

Edit: amalloy is quite right, clojure.string/join is a much more efficient implementation.

What I did above is what was in clojure.contrib v1.0 str-join (I suspect that my memory was playing tricks on me and that is where I saw interpose used in the first place).

0

精彩评论

暂无评论...
验证码 换一张
取 消