美文网首页
随机生成任意长度字符串

随机生成任意长度字符串

作者: 穿长裙的年代 | 来源:发表于2021-04-07 13:47 被阅读0次
public static String getRandomString(int length){
            //定义一个字符串(A-Z,a-z,0-9)即62位;
            String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
            //由Random生成随机数
            Random random=new Random();
            StringBuffer sb=new StringBuffer();
            //长度为几就循环几次
            for(int i=0; i<length; ++i){
                //产生0-61的数字
                int number=random.nextInt(62);
                //将产生的数字通过length次承载到sb中
                sb.append(str.charAt(number));
            }
            //将承载的字符转换成字符串
            return sb.toString();
        }

相关文章

网友评论

      本文标题:随机生成任意长度字符串

      本文链接:https://www.haomeiwen.com/subject/xxmucltx.html