生成随机字符串 随机字符串/密码生成器

随机字符串/密码生成器,输入位数,选择生成选项,也可以自定义输入文本,点击生成即可产生随机字符串/密码

  • 位数
  • 个数

用代码生成随机字符串 javascript、php、java、ruby、go、c、python

Javascript 代码生成随机字符串

function getRandomString(length) {
    const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let str = '';
    for (let i = 0; i < length; i++) {
        str += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return str;
}

php 代码生成随机字符串

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charLength - 1)];
    }
    return $randomString;
}

Java 代码生成随机字符串

private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// 生成指定长度的随机字符串,可包含大写和小写字母和数字
public static String getRandomString(int length) {
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        int index = random.nextInt(CHARACTERS.length());
        sb.append(CHARACTERS.charAt(index));
    }
    return sb.toString();
}

Ruby 代码生成随机字符串

def generate_random_string(length)
    chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
    Array.new(length) { chars.sample }.join
end

C 代码生成随机字符串

#include 
#include 
#include 
#include 

char* generate_random_string(int length) {
    char* str = (char*) malloc(length + 1);
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    srand(time(NULL));
    for (int i = 0; i < length; i++) {
        int index = rand() % strlen(charset);
        str[i] = charset[index];
    }
    str[length] = '\0';
    return str;
}

Go 代码生成随机字符串

import (
    "math/rand"
    "time"
)

func generateRandomString(length int) string {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    rand.Seed(time.Now().UnixNano())
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[rand.Intn(len(charset))]
    }
    return string(b)
}

Python 代码生成随机字符串

import random
import string

def generate_random_string(length):
    letters = string.ascii_lowercase + string.ascii_uppercase + string.digits
    return ''.join(random.choice(letters) for i in range(length))