java获取指定位数的不重复随机字符串

原创  郑建华   2021-09-28   60人阅读  0 条评论

获取指定位数随机字符串,字符串由数字和字母组成

// 随机字符数组
public static String[] randomArray ={"1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z"};

/**
 * 获取指定位数随机字符串,字符串由数字和字母组成
 * @param num
 * @return
 */
public static String getRandomStringByNum(int num){
    StringBuilder sbr=new StringBuilder();
    // 创建一个随机数
    Random random=new Random();
    // 遍历随机数位数
    for(int i=0;i<num;i++){
        // 获取一个数组下标的随机数
        Integer index = random.nextInt(randomArray.length);
        // 递归调用 获取不重复的随机字符添加到字符串中
        getRandomString(sbr,index,random);
    }
    return sbr.toString();
}

/**
 * 获取不重复的随机字符添加到字符串中
 * @param resultStr
 * @param index
 * @param random
 */
public static void getRandomString(StringBuilder resultStr,int index,Random random){
    // 获取随机字符
    String randomChart = randomArray[index];
    // 当前已包含随机字符
    if(resultStr.indexOf(randomChart)!=-1){
        // 获取一个数组下标的随机数
        index = random.nextInt(randomArray.length);
        // 递归调用,重新获取新的随机字符
        getRandomString(resultStr,index,random);
    // 未包含随机字符
    }else{
        // 则将字符添加到字符串中
        resultStr.append(randomChart);
    }
}


本文地址:https://www.zjh336.cn/?id=2061
版权声明:本文为原创文章,版权归 郑建华 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?