com.ideaaedi.commonds.chars.CharUtil Maven / Gradle / Ivy
The newest version!
package com.ideaaedi.commonds.chars;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* util for char
*
* @author JustryDeng
* @since 1.0.0
*/
public class CharUtil {
public static final Character[] CHAR_POOL = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'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', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '.'
};
/**
* 生成指定长度的随机字符串
*
* @param length
* 长度
* @return 字符数组
*/
public static char[] generateCharArr(Character[] chars, int length) {
if (chars == null || chars.length == 0) {
throw new IllegalArgumentException("char cannot be empty.");
}
char[] result = new char[length];
List list = Arrays.asList(chars);
// "洗牌"
Collections.shuffle(list);
Random random = new SecureRandom();
for (int i = 0; i < length; i++) {
if (i < chars.length) {
result[i] = list.get(i);
} else {
result[i] = list.get(random.nextInt(chars.length));
}
}
return result;
}
/**
* 生成指定长度的随机字符串
*
* @see CharUtil#generateCharArr(Character[], int)
*/
public static char[] generateCharArr(int length) {
return generateCharArr(CHAR_POOL, length);
}
}