问题
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