Ever needed to generate a random password, token, or unique ID for your app? You’re not alone — this is one of the most common tasks in programming, no matter the language you use. Every programming language has a simple way to generate random strings — whether you’re coding in Python, PHP, JavaScript, Java, C#, or Go.
Below is a handy reference showing how to do it in multiple popular programming languages. You copy, tweak, and use them in your projects. Each snippet is designed to generate a single random string of 10 characters. Here we go!
Assembly
; Pseudo-random example (x86 NASM)
section .data
msg db "Random String:", 10, 0
section .text
global _start
_start:
mov ecx, 10 ; length
.loop:
mov eax, 1
int 0x80 ; (stub for random generator)
loop .loopBash
Linux:
# Random string of 10 characters
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 10C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int length = 10;
char str[length + 1];
srand(time(NULL));
for (int i = 0; i < length; i++)
str[i] = charset[rand() % (sizeof(charset) - 1)];
str[length] = '\0';
printf("%s\n", str);
return 0;
}C++
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
string result;
srand(time(0));
for (int i = 0; i < 10; i++)
result += chars[rand() % chars.size()];
cout << result << endl;
}C#
using System;
using System.Linq;
class Program {
static void Main() {
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
var result = new string(Enumerable.Repeat(chars, 10)
.Select(s => s[random.Next(s.Length)]).ToArray());
Console.WriteLine(result);
}
}PowerShell
Windows:
-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 10 | % {[char]$_})CMD
Windows:
@echo off
setlocal enabledelayedexpansion
set chars=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
set str=
for /L %%i in (1,1,10) do (
set /A rnd=!random! %% 62
for %%a in (!rnd!) do set str=!str!!chars:~%%a,1!
)
echo %str%Dart
import 'dart:math';
void main() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
final rand = Random();
final result = List.generate(10, (_) => chars[rand.nextInt(chars.length)]).join();
print(result);
}Go
package main
import (
"math/rand"
"time"
"fmt"
)
func main() {
rand.Seed(time.Now().UnixNano())
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, 10)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
fmt.Println(string(b))
}Java
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom rnd = new SecureRandom();
StringBuilder sb = new StringBuilder(10);
for (int i = 0; i < 10; i++)
sb.append(chars.charAt(rnd.nextInt(chars.length())));
System.out.println(sb);
}
}JavaScript
const randomString = Math.random().toString(36).substring(2, 12);
console.log(randomString);Node.js (crypto version)
const crypto = require('crypto');
console.log(crypto.randomBytes(8).toString('hex').substring(0, 10));Kotlin
import kotlin.random.Random
fun main() {
val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
val result = (1..10)
.map { chars[Random.nextInt(chars.length)] }
.joinToString("")
println(result)
}PHP
<?php
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$result = '';
for ($i = 0; $i < 10; $i++) {
$result .= $characters[random_int(0, strlen($characters) - 1)];
}
echo $result;Python
import secrets, string
print(''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(10)))R
chars <- c(letters, LETTERS, 0:9)
result <- paste(sample(chars, 10, replace=TRUE), collapse="")
print(result)
React
(Same as JavaScript)
const randomString = Math.random().toString(36).substring(2, 12);
console.log(randomString);Ruby
chars = [*'A'..'Z', *'a'..'z', *'0'..'9']
puts (0...10).map { chars.sample }.joinRust
use rand::{distributions::Alphanumeric, Rng};
fn main() {
let s: String = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.map(char::from)
.collect();
println!("{}", s);
}SQL
MySQL
SELECT SUBSTRING(MD5(RAND()), 1, 10) AS random_string;PostgreSQL:
SELECT substr(md5(random()::text), 1, 10);SQL Server
SELECT SUBSTRING(CONVERT(varchar(40), NEWID()), 1, 10) AS RandomString;Swift
import Foundation
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let result = String((0..<10).map { _ in letters.randomElement()! })
print(result)Perl
use strict;
use warnings;
my @chars = ('A'..'Z', 'a'..'z', 0..9);
my $string;
$string .= $chars[rand @chars] for 1..10;
print "$string\n";Visual Basic
Module Module1
Sub Main()
Dim chars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim rand As New Random()
Dim result As String = ""
For i As Integer = 1 To 10
result &= chars(rand.Next(chars.Length))
Next
Console.WriteLine(result)
End Sub
End ModuleWrapping Up
Random string generation is universal — every programming language handles it differently, but the concept is always the same: pick random characters from a set and combine them.
Bookmark this post as your quick reference guide, and the next time you need a random ID or password, you’ll have the code ready.