commons-text 生成指定长度的随机字符串

时间:2025-01-16 13:06:26
package com.skylink.junge.demo;

import java.util.HashSet;
import java.util.Set; import org.apache.commons.text.RandomStringGenerator;
import org.apache.commons.text.StrTokenizer; public class StrTokenizerTest { public static void main(String[] args) {
StrTokenizer strTokenizer = new StrTokenizer("a,b,c", ',');
while (strTokenizer.hasNext()) {
System.out.println(strTokenizer.next());
} strTokenizer = new StrTokenizer("a\nb\nc");
while (strTokenizer.hasNext()) {
System.out.println(strTokenizer.next());
} StrTokenizer tsvTokenizer = StrTokenizer.getCSVInstance(" a, b , c ");
while (tsvTokenizer.hasNext()) {
System.out.println(tsvTokenizer.next());
} int count = 10000;
Set<String> result = new HashSet<String>(count);
RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('0', '9').build();
for (int i=0; i<count; i++) {
result.add(generator.generate(20));
} if (count != result.size()) {
System.out.println("repeat str");
}
System.out.println(result.size());
} }

输出结果:

commons-text 生成指定长度的随机字符串