1. 程式人生 > >Java生成指定長度並且包含大小寫字母數字字串示例

Java生成指定長度並且包含大小寫字母數字字串示例

public class JUID {
/**
* 隨機生成輸入長度的字串,生成策略:前序列位[A-Z]-[0-9]-[a-z]{length/3},後餘位隨機
* @param length 所要生成的字串長度
* @return String 生成的隨機字串
*/
public String createUID(int length){
if(length<3){//如果輸入的長度小於3,那麼就返回空字串
return "";
}
char[] ss = new char[length];//存放生成的字串
int i=0;
int index = 0;//索引位置
int standard = length/3;//前幾位必須包含大小寫字母數字
//標準隨機策略,可做相應更改
while(i<standard) {
ss[index] = (char) ('A'+Math.random()*26);//隨機一個大寫字母
ss[index+1] = (char) ('0'+Math.random()*10); //隨機一個數字
ss[index+2] = (char) ('a'+Math.random()*26); //隨機一個小寫字母
   i++;
   index = index+3;
   }
//後續位數隨機生成
while(index<length){
int f = (int) (Math.random()*length);//生成隨機長度數
   if(f>index-1)  
    ss[index] = (char) ('A'+Math.random()*26);
   else if(f>index-3)  
    ss[index] = (char) ('a'+Math.random()*26);
   else 
    ss[index] = (char) ('0'+Math.random()*10);
   index++;
}
return new String(ss);
}


/**
* @param args
*/
public static void main(String[] args) {
JUID juuid = new JUID();
int length = 3;
String str = juuid.createUID(length);
System.out.println(str);
}


}