继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java中创建随机长度的字符串(借鉴别人的)

qq_人之翘楚_0
关注TA
已关注
手记 14
粉丝 0
获赞 16
private static Random randGen = null;
    private static char[] numbersAndLetters = null;

    public static final String randomString(int length) {
             if (length < 1) {
                 return null;
             }
             if (randGen == null) {
                    randGen = new Random();
                    numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
                       "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                      //numbersAndLetters = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                     }
             char [] randBuffer = new char[length];
             for (int i=0; i<randBuffer.length; i++) {
                 randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
              //randBuffer[i] = numbersAndLetters[randGen.nextInt(35)];
             }
             return new String(randBuffer);
    }

    //调用此方法randomString(int),int是字符串的长度,即可产生指定长度的随机字符串。
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP