How to generate random alphanumeric string in julia?

∥☆過路亽.° 提交于 2021-02-08 19:44:44

问题


I am trying to generate 12 characters alphanumeric string in julia with the following snippets:
a)
an = randstring(rand(Bool) ? ('A':'Z') : ('0':'9'), 12)
b)

an = "" 
for i in [1:12]
    an *= randstring(rand(Bool) ? ('A':'Z') : ('0':'9'))
end

but both gives either complete 12 digits or 12 alphabets but not of their combination.

please guide me in generating combination of 12 alphanumeric string.


回答1:


If you don't mind using both upper and lower case letters, you can simply call randstring(12):

julia> using Random

julia> randstring(12)
"0IPrGg0JVONT"

julia> randstring(12)
"EB5dhw4LVno7"

If you want only uppercase letters (and numbers), then you need to pass randstring a collection that includes only uppercase letters and numbers, which you can achieve with ['A':'Z'; '0':'9']:

julia> randstring(['A':'Z'; '0':'9'], 12)
"ASZQAT5YX3OL"

julia> randstring(['A':'Z'; '0':'9'], 12)
"FEV5HTGMLQ6X"

Finally, note that you could provide the collection of characters as a string:

julia> randstring("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 12)
"ASZQAT5YX3OL"


来源:https://stackoverflow.com/questions/56453509/how-to-generate-random-alphanumeric-string-in-julia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!