获取指定位数随机字符串,字符串由数字和字母组成
// 随机字符数组 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); } }
还没有评论,来说两句吧...