package com.v2ex.random1;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
/**
* Created by corning on 2018/1/29.
*/
public class Random1 {
public static final String A_Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 生成随机字符串,包含 A-Z 和指定数字
*
* @
param fullLen 字符串总长度
* @
param num 指定的数字
* @
param numLen 指定数字出现最大次数
* @
return */
public static String randomAlphabetWithNum(int fullLen, int num, int numLen) {
// 数字出现次数是随机的
int numRealLen = RandomUtils.nextInt(1, numLen);
// 根据数字出现次数,计算字符串出现次数
int strRealLen = fullLen - numRealLen;
String randomStr = RandomStringUtils.random(strRealLen, A_Z);
// 在字符串中,随机获取下标并插入数字
StringBuffer sb = new StringBuffer(randomStr);
for (int i = 0; i < numRealLen; i++) {
int randomOffset = RandomUtils.nextInt(0, sb.length() + 1);
sb.insert(randomOffset, num);
}
return sb.toString();
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Random1.randomAlphabetWithNum(35, 5, 5));
}
}
}
// 测试结果
// LMKABJN5YTKICAXS5E55ZXHJOBQTJQPVXYT
// RVLGQJHSQSXGXGXSOIIHRNLBPBYCPBBWY5L
// KUFB5RNCHTNSYUPPUD5NDGIVFHR5RCCLFVQ
// GJJMJGAEFPXEA5MZS5YTNBUHO5DWCXKJYSB
// UIDXJPI5QOKF5QNPUUCDCZ5JDKTDZYJPUDI
// FIBULFHIY5ZJH5XRZOMKN5EHEJOPDUECCTL
// U5YDH5RRIRXEVNRPCEP5PNSKBGPQWGV5CBJ
// SEQ5LAFZT55WKBRKBLSJBA5FYQJSHZJLNBM
// MVW5NT5RJAUVHSKLQKMDKARSHHBRNRKGGAW
// VKZIKYRXSW5XIOGR5AEFBRMKWFZV5LIORMZ