欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取随机字符串(Clojure)

程序员文章站 2022-07-14 19:26:34
...
处女贴,不知道写什么,把今天在群里讨论的贴上来好了。

 (defn ^String rand-str [N] 
(loop [sb (StringBuilder. "")
x N
s (get "0123456789" (rand-int 10))]
(if (> x 0)
(recur (-> sb (.append s)) (- x 1)
(get "0123456789" (rand-int 10)))
(str sb)))
)

(rand-str 15)


这个是我写的,不喜欢(get "0123456789" (rand-int 10)) 两次,又改:
  (defn ^String rand-str [N] 
(loop [sb (StringBuilder. "")
x ( + 1 N)
s \ ]
(if (> x 0)
(recur (-> sb (.append s)) (- x 1)
(get "abcdefghijklmnopqrstuvwxyz0123456789" (rand-int 37)))
(clojure.string/trim sb)))
)

(rand-str 10)


不过我觉得群友的更简洁一些:
  (defn rand-str [n] 
(clojure.string/join (repeatedly n
#(rand-nth "abcdefghijklmnopqrstuvwxyz0123456789"))))
(rand-str 10)


还有人这样写:
(subs (str (Object.)) 17)