您的位置:首页 > 其它

随机产生由特殊字符,大小写字母以及数字组成的字符串,且每种字符都至少出现一次

2016-08-02 00:00 218 查看

题目:随机产生字符串,字符串中的字符只能由特殊字符 (!@#$%), 大写字母(A-Z),小写字母(a-z)以及数字(0-9)组成,且每种字符至少出现一次。

这样产生字符串的方式可以应用到如下场景,比如,我们有一个应用就是添加用户完毕之后,发邮件给指定用户包括一个长度为11位的初始化密码。

1. 我们先来定义一个包含这四种字符类型的char数组

private static final char[] symbols;

static {
StringBuilder tmp = new StringBuilder();
for (char ch = '0'; ch <= '9'; ++ch)
tmp.append(ch);
for (char ch = 'a'; ch <= 'z'; ++ch)
tmp.append(ch);
for (char ch = 'A'; ch <= 'Z'; ++ch)
tmp.append(ch);

// 添加一些特殊字符
tmp.append("!@#$%");
symbols = tmp.toString().toCharArray();
}

详细代码如下

import java.util.Random;

public class RandomAlphaNumericGenerator {
private static final char[] symbols; static { StringBuilder tmp = new StringBuilder(); for (char ch = '0'; ch <= '9'; ++ch) tmp.append(ch); for (char ch = 'a'; ch <= 'z'; ++ch) tmp.append(ch); for (char ch = 'A'; ch <= 'Z'; ++ch) tmp.append(ch); // 添加一些特殊字符 tmp.append("!@#$%"); symbols = tmp.toString().toCharArray(); }

private final Random random = new Random();

private final char[] buf;

public RandomAlphaNumericGenerator(int length) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}

public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}

2. 根据步骤1中产生的字符数组,随机产生一个字符串,判断其是否至少包含一个特殊字符、一个数字、一个小写字母以及一个大写字母,如果不是,则重新产生一个新的随机字符串直到产生符合条件的随机字符串为止

在这里,我们使用正则表达式的方式验证字符串是否符合要求,正则表达式为 .*(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%]).*

测试代码如下:

public class RandomAlphaNumericGeneratorTest {
public static void main(String[] args) {
RandomAlphaNumericGenerator randomTest = new RandomAlphaNumericGenerator(11);
for(int i=0;i<10;i++){
String result = null;
do {
result = randomTest.nextString();
} while (!result.matches(".*(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%]).*"));
System.out.println(result);
}
System.out.println();

}
}

某一次运行的结果如下:

u7YMTR4!o$!
H004vVb!W9Z
RLnhzUpYl6$
@UFDysu7qBa
%2edSPri$e2
KY9!HPtcWlX
ciVns$DMIN9
j6BU%heDIHp
Nmn8747#$Vd
oLp@DDUxH8d

本文原文地址 http://thecodesample.com/?p=935
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐