Skip to content

Instantly share code, notes, and snippets.

@pfmiles
Created November 16, 2015 07:58
Show Gist options
  • Save pfmiles/12a5359d76056de9eead to your computer and use it in GitHub Desktop.
Save pfmiles/12a5359d76056de9eead to your computer and use it in GitHub Desktop.
随机字符串生成器,字符集为ascii可打印字符
package test;
import java.util.Random;
/**
* 生成指定长度的随机串,字符范围仅限于ascii可打印字符: https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
* @author pf-miles Nov 16, 2015 3:18:13 PM
*/
public abstract class RandomPrintableStringGenerator {
private static final Random r = new Random();
// 33 ~ 126是ascii可见字符
private static final char[] cs = new char[126 - 32];
static {
for (int i = 0; i < cs.length; i++) {
cs[i] = (char) (i + 33);
}
}
/**
* 生成指定长度的随机串, 字符范围为ascii可打印字符
* @param length
*/
public static String randString(int length) {
if (length < 1 || length > 128)
throw new IllegalArgumentException("Illegal random string length.");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
sb.append(cs[r.nextInt(cs.length)]);
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment