Hutool 生成随机数和随机字符串

官方文档: https://www.hutool.cn/docs/#/core/工具类/随机工具-RandomUtil

1.原生Java代码实现:

private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 数字和26个字母组成
private static final Random RANDOM = new SecureRandom(); // SecureRandom是加密且线程安全的

/**
 * 获取长度为 6 的随机字母+数字
 * @return 随机数字
 */
public static String getRandomNumber() {
    char[] nonceChars = new char[16];  //指定长度为6位/自己可以要求设置

    for (int index = 0; index < nonceChars.length; ++index) {
        nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
    }
    return new String(nonceChars);
}


2.Hutool工具实现:

public static void main(String[] args) {
    // 小写字母+数字,例:d2qdw920d5
    String randomString1 = RandomUtil.randomString(10);
    // 大写字母+数字,例:I6R7Q38JWC
    String randomStringUpper = RandomUtil.randomStringUpper(10);
    // 只含有abc,例:bcccbcccac
    String randomString2 = RandomUtil.randomString("abc", 10);
    // 大写字母+小写字母+数字,例:qf0Vr2TK3J
    String randomString3 = RandomUtil.randomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 10);
    // 数字,例:8
    char randomNumber1 = RandomUtil.randomNumber();
    // 小写字母+大写字母中,不含有0123456789,例:nmjjyscmvq
    String randomStringWithoutStr = RandomUtil.randomStringWithoutStr(10, "0123456789");
    // 生成小写字母+数字的其中一个字符,例:m
    char randomChar1 = RandomUtil.randomChar();
    // 生成0123456789中一个字符,例:7
    char randomNumber2 = RandomUtil.randomNumber();
    // 生成-!?中一个字符,例:?
    char randomChar2 = RandomUtil.randomChar("-!?");
}

整理完毕,完结撒花~

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不愿放下技术的小赵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值