Logo

Programming-Idioms

Create a string s of n characters having uniform random values out of the 62 alphanumeric values A-Z, a-z, 0-9
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
import "math/rand"
const alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func randomString(n int) string {
	a := make([]byte, n)
	for i := range a {
		a[i] = alphanum[rand.Intn(len(alphanum))]
	}
	return string(a)
}
import "math/rand"
const alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func randomString(n int, rng *rand.Rand) string {
	a := make([]byte, n)
	for i := range a {
		a[i] = alphanum[rng.Intn(len(alphanum))]
	}
	return string(a)
}
import "math/rand"
var alphanum = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")

func randomString(n int, rng *rand.Rand) string {
	a := make([]rune, n)
	for i := range a {
		a[i] = alphanum[rng.Intn(len(alphanum))]
	}
	return string(a)
}
const s = ((n) => {
    const alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let s = "";
    for (let i = 0; i < n; i += 1) {
        s += alphanum[~~(Math.random() * alphanum.length)];
    }
    return s;
})(n);
import static java.util.Arrays.asList;
import static java.util.Collections.shuffle;
String s = "";
Integer z[], i = 0;
char a[] = new char[62], c;
for (c = 'a'; c <= 'z'; ++c) a[i++] = c;
for (c = 'A'; c <= 'Z'; ++c) a[i++] = c;
for (c = '0'; c <= '9'; ++c) a[i++] = c;
z = new Integer[62];
for (i = 0; i < 62; ++i) z[i] = i;
shuffle(asList(z));
for (i = 0; i < n; ++i) s = s + a[z[i]];
function RandomString(Size: Integer): String;
const
  Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  Len = Length(Chars);
var
  i: Integer;
begin
  Result := '';
  SetLength(Result, Size);
  for i := 1 to Size do
  begin
    Result[i] := Chars[Random(Len)+1];
  end;
end; 
my @chars = ('A'..'Z', 'a'..'z', '0'..'9'); 
my $s=''; 
$s .= $chars[int rand @chars] for 1..$n;
import random
import string
alphanum = string.ascii_letters + string.digits
s = ''.join(random.choices(alphanum, k=n))
import random as r, string as s
a = list(s.ascii_letters + s.digits)
r.shuffle(a)
s = ''.join(a[:n])
require 'securerandom'
s = SecureRandom.alphanumeric(n)
use rand::distributions::Alphanumeric;
use rand::Rng;
fn random_string(n: usize) -> String {
    rand::thread_rng()
        .sample_iter(Alphanumeric)
        .take(n)
        .map(char::from)
        .collect()
}
use rand::distributions::{Alphanumeric, DistString};
fn random_string(n: usize) -> String {
    Alphanumeric.sample_string(&mut rand::thread_rng(), n)
}