生成指定长度及类型的字符串

385 阅读1分钟

思路:

想要生成随机字母首先得到字母所对应的ASCII码,然后通过强转为char来得到对应的字母;

通过字符类型来限定生成的随机数范围;

通过代码类型来限定可使用的字符类型.

import java.util.concurrent.ThreadLocalRandom;

public class RandomStringUtil {

    private RandomStringUtil(){}

    /*
        通过字符类型传入的范围来生成随机数,
        将随机数转换为对应的字符
     */
    public static String gen(LetterType letterType){
        int max = letterType.max;
        int min = letterType.min;
        int rn = ThreadLocalRandom.current().nextInt(min, max + 1);
        return String.valueOf((char)rn);
    }

    /*
        通过长度来控制生成字符的次数
        通过codeType来传入生成类型的集合
        通过随机数来随机选择其中一种类型生成字符然后拼接
     */
    public static String genCode(int length,CodeType codeType){
        StringBuilder stringBuilder = new StringBuilder(length);
        LetterType[] letterTypes = codeType.letterTypes;
        for(int i=0;i<length;i++){
            int rn = ThreadLocalRandom.current().nextInt(letterTypes.length);
            stringBuilder.append(gen(letterTypes[rn]));
        }
        return stringBuilder.toString();
    }

    /*
        验证码类型:
            1\. 纯数字
            2\. 纯大写字母
            3\. 纯小写字母
            4\. 大小写混合字母
            5\. 字母数字混合
     */
    public enum CodeType{

        UPPER_CASE_LETTERS(new LetterType[]{LetterType.UPPER_CASE_LETTER}),
        LOWER_CASE_LETTERS(new LetterType[]{LetterType.LOWER_CASE_LETTER}),
        NUMBER(new LetterType[]{LetterType.NUMBER}),
        MIX_LETTERS(new LetterType[]{LetterType.UPPER_CASE_LETTER,LetterType.LOWER_CASE_LETTER}),
        MIX(new LetterType[]{LetterType.UPPER_CASE_LETTER,LetterType.LOWER_CASE_LETTER,LetterType.NUMBER});

        private LetterType[] letterTypes;

        CodeType(LetterType[] letterTypes){
            this.letterTypes = letterTypes;
        }

    }

    /*
        定义大写字母小写字母在ASCII码中的范围
        数字48-57
        大写字母65-90
        小写字母97-122
     */
    public enum LetterType{
        NUMBER(57,48),
        UPPER_CASE_LETTER(90,65),
        LOWER_CASE_LETTER(122,97);

        private int max;
        private int min;

        LetterType(int max,int min){
            this.max = max;
            this.min = min;
        }
    }
}

tip:

随机数的生成使用的1.8的新特性,如果是1.7及以前的可以修改gen方法中生成随机数部分的代码,具体如下:

Random random = new Random();
int rn = random.nextInt(max-min+1)+min;