随机字符串工具类

示例代码:

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.*;

/**
 * 随机生成字符串
 */
public final class RandomStringUtil {
    /**
     * 2021年姓排行100
     */
    private final static String[] SURNAME = {
        "李", "王", "张", "刘", "陈",
        "杨", "赵", "黄", "周", "吴",
        "徐", "孙", "胡", "朱", "高",
        "林", "何", "郭", "马", "罗",
        "梁", "宋", "郑", "谢", "韩",
        "唐", "冯", "于", "董", "萧",
        "程", "曹", "袁", "邓", "许",
        "傅", "沈", "曾", "彭", "吕",
        "苏", "卢", "蒋", "蔡", "贾",
        "丁", "魏", "薛", "叶", "阎",
        "余", "潘", "杜", "戴", "夏",
        "钟", "汪", "田", "任", "姜",
        "范", "方", "石", "姚", "谭",
        "廖", "邹", "熊", "金", "陆",
        "郝", "孔", "白", "崔", "康",
        "毛", "邱", "秦", "江", "史",
        "顾", "侯", "邵", "孟", "龙",
        "万", "段", "漕", "钱", "汤",
        "尹", "黎", "易", "常", "武",
        "乔", "贺", "赖", "龚", "文"};

    private static final char LOWER_CHAR[] = {'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'};
    private static final char UPPER_CHAR[] = {'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'};
    private static final char NUMBER_CHAR[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    public static final int MULTIPLE = 0;// 所有字符
    public static final int LOWER = 1;// 只包含小写字母
    public static final int UPPER = 2;// 只包含大写字母
    public static final int NUMBER = 3;// 只包含数字
    public static final int LOWER_AND_UPPER = 4;// 包含大小写字母
    public static final int LOWER_AND_NUMBER = 5;// 包含小写字母和数字
    public static final int UPPER_AND_NUMBER = 6;// 包含大写字母和数字

    /**
     * 随机获取姓名
     *
     * @return
     */
    public static String fullName() {
        return surname() + name(2);
    }

    /**
     * 拼接字符数组
     */
    public static char[] concat(char[]... a) {
        LinkedList<Character> list = new LinkedList<>();
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                list.add(a[i][j]);
            }
        }
        char result[] = new char[list.size()];
        Iterator<Character> it = list.iterator();
        for (int i = 0, length = result.length; i < length; i++) {
            result[i] = it.next();
        }
        return result;
    }

    /**
     * 获取随机字符串,包含大小写字母和数字,可以有重复字符
     *
     * @param length 字符串长度
     */
    public String getRandomString(int length) {
        return getRandomString(length, MULTIPLE, true);
    }

    /**
     * 获取随机字符串,可以有重复字符
     *
     * @param length     字符串长度
     * @param randomType 随机字符的类型
     */
    public String getRandomString(int length, int randomType) {
        return getRandomString(length, randomType, true);
    }

    /**
     * 获取随机字符串
     *
     * @param length     字符串长度
     * @param randomType 随机字符的类型
     * @param repeat     是否可以有重复字符,true表示可以重复,false表示不允许重复。如果length大于randomType库的长度,则默认采用true值。
     */
    public static String getRandomString(int length, int randomType, boolean repeat) {
        StringBuilder sb = new StringBuilder();
        char find[] = null;
        switch (randomType) {
            case LOWER:
                find = LOWER_CHAR;
                break;
            case UPPER:
                find = UPPER_CHAR;
                break;
            case NUMBER:
                find = NUMBER_CHAR;
                break;
            case MULTIPLE:
                find = concat(LOWER_CHAR, UPPER_CHAR, NUMBER_CHAR);
                break;
            case LOWER_AND_NUMBER:
                find = concat(LOWER_CHAR, NUMBER_CHAR);
                break;
            case UPPER_AND_NUMBER:
                find = concat(UPPER_CHAR, NUMBER_CHAR);
                break;
            case LOWER_AND_UPPER:
                find = concat(LOWER_CHAR, UPPER_CHAR);
                break;
        }
        if (length > find.length) {
            repeat = true;
        }
        final SecureRandom r = new SecureRandom();
        if (repeat) {
            for (int i = 0; i < length; i++) {
                sb.append(find[r.nextInt(find.length)]);
            }
        } else {
            HashSet<Integer> indexset = new HashSet<Integer>();
            for (int i = 0; i < length; i++) {
                int index = r.nextInt(find.length);
                while (indexset.contains(index)) {
                    index = r.nextInt(find.length);
                }
                sb.append(find[index]);
                indexset.add(index);
            }
        }
        return sb.toString();
    }

    /**
     * 获取随机字符串
     *
     * @param length 字符串长度
     * @param repeat 是否可以存在重复的字符
     * @param ch     自定义字符集
     */
    public static String getRandomString(int length, boolean repeat, char[]... ch) {
        List<Character> list = new LinkedList();
        for (char[] cs : ch) {
            for (char c : cs) {
                list.add(c);
            }
        }
        if (list.size() == 0) {
            return "";
        }
        if (length > list.size()) {
            repeat = true;
        }
        final SecureRandom r = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            if (repeat) {
                sb.append(list.get(r.nextInt(list.size())));
            } else {
                sb.append(list.remove(r.nextInt(list.size())));
            }
        }
        return sb.toString();
    }


    /**
     * 随机获取姓
     *
     * @return
     */
    private static String surname() {
        return SURNAME[new Random().nextInt(SURNAME.length - 1)];
    }

    /**
     * 获取N位常用字
     *
     * @param len
     * @return
     */
    private static String name(int len) {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String str = null;
            // 定义高低位
            int highPos, lowPos;
            Random random = new Random();
            //获取高位值
            highPos = (176 + Math.abs(random.nextInt(39)));
            //获取低位值
            lowPos = (161 + Math.abs(random.nextInt(93)));
            byte[] b = new byte[2];
            b[0] = (new Integer(highPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                //转成中文
                str = new String(b, "GBK");
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret.append(str);
        }
        return ret.toString();
    }

    public static void main(String[] args) {
        System.out.println(RandomStringUtil.fullName());
    }
}

 

posted @ 2022-06-09 15:23  残城碎梦  阅读(43)  评论(0编辑  收藏  举报