获取随机字符串(Clojure)
程序员文章站
2022-07-14 19:26:34
...
处女贴,不知道写什么,把今天在群里讨论的贴上来好了。
这个是我写的,不喜欢(get "0123456789" (rand-int 10)) 两次,又改:
不过我觉得群友的更简洁一些:
还有人这样写:
(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)
上一篇: PHP获取随机字符串
下一篇: php获取随机字符串