例如:randomString(5) -> hi2Pd
方法一:按照ASCII值判断数字字母下划线的范围
public static StringBuffer randomString2(int num){
//数字范围【0,9】,小写字母范围【97,122】,大写字母【65,90】,下划线95
int temp;
StringBuffer stringBuffer=new StringBuffer();
while(stringBuffer.length()<5){
temp=(int)(Math.random()*123);
if(temp>=48&&temp<=57||temp>=97&&temp<=122||temp>=65&&temp<=90||temp==95){
// System.out.println(temp);
stringBuffer.append((char)temp);
}
}
return stringBuffer;
}
方法二:将字母数字下划线存入到一个字符数组中,随机生成下标组成字符串.
public static StringBuffer randomString(int num){ StringBuffer stringBuffer=new StringBuffer(); int randomIndex; char []randomChar={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','0','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','_'}; for(int i=0;i<num;i++) { randomIndex = (int) (Math.random() * randomChar.length); stringBuffer.append(String.valueOf(randomChar[randomIndex])); } return stringBuffer; }