您的位置 首页 java

Java随机生成数字+字母组合的字符串

Talk is cheap, Show me the code. — by: Linus Torvalds

方式一、

使用UUID,缺点长度固定。

 public static String generateString() {
    // .replaceAll("-", "") 去掉 uuid 中的 “-”
    return UUID.randomUUID().toString().replaceAll("-", "");
}  

方式二、

长度任意,且可定制。

     static final String string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static Random rnd = new Random();
    public static String randomString(int len) {
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++)
            sb.append(string.charAt(rnd.nextInt(string.length())));
        return sb.toString();
    }  

文章来源:智云一二三科技

文章标题:Java随机生成数字+字母组合的字符串

文章地址:https://www.zhihuclub.com/169228.shtml

关于作者: 智云科技

热门文章

网站地图