import java.util.Random;
/**
* Created by Pritom K Mondal.
*/
public class RandomString {
public static String formatAsLength(Long number, Integer minLength = 0) {
return String.format("%0${minLength}d%n".toString(), number).trim();
}
private static final char[] symbols = new char[62];
private static final char[] chars = new char[52];
private static final char[] numbers = new char[10];
static {
initialize();
}
public static void initialize() {
Integer symIdx = 0, numIdx = 0, charIdx = 0;
for (int idx = 48; idx <= 57; ++idx) {
symbols[symIdx++] = (char) (idx);
numbers[numIdx++] = (char) (idx);
}
for (int idx = 97; idx < 26 + 97; ++idx) {
symbols[symIdx++] = (char) (idx);
chars[charIdx++] = (char) (idx);
}
for (int idx = 65; idx < 26 + 65; ++idx) {
symbols[symIdx++] = (char) (idx);
chars[charIdx++] = (char) (idx);
}
}
private static Random random = new Random();
public static String nextString(int length) {
if (length < 1) {
throw new IllegalArgumentException("length < 1: " + length);
}
if (symbols[0] == (char) 0) {
initialize();
}
String returnString = "";
for (int idx = 0; idx < length; ++idx) {
returnString += symbols[random.nextInt(symbols.length)].toString()
}
return returnString;
}
public static String nextNumber(int length) {
if (length < 1) {
throw new IllegalArgumentException("length < 1: " + length);
}
if (symbols[0] == (char) 0) {
initialize();
}
char[] buf = new char[length];
for (int idx = 0; idx < buf.length; ++idx) {
buf[idx] = numbers[random.nextInt(numbers.length)];
}
return new String(buf);
}
public static String nextCharacter(int length) {
if (length < 1) {
throw new IllegalArgumentException("length < 1: " + length);
}
if (symbols[0] == (char) 0) {
initialize();
}
char[] buf = new char[length];
for (int idx = 0; idx < buf.length; ++idx) {
buf[idx] = chars[random.nextInt(chars.length)];
}
return new String(buf);
}
}
No comments:
Post a Comment