I faced some difficulties to figure out how to generate unique string within [1;200) range length. The code I've come up with attached below:
public static String generateRandString() {
String STRING_TOKENS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
while(stringBuilder.length() <= 200) {
int index = (int) random.nextFloat() * STRING_TOKENS.length();
stringBuilder.append(STRING_TOKENS.charAt(index));
}
return stringBuilder.toString();
}
The Problem:
Requesting 20 generated strings returns every time "AAAAAAAA" string probably of 200 symbols length
Expected output:
A7898as7sd6as5da
as87asd67
768asjhg435GhA900324
2g2j3h4gjhgAKL*78a9dd879234
3B234
1
Some limitations:
Many thanks to your contribution!
Try this !!!
for (int i = 0; i < 10; i++)
System.out.println(randomString(ThreadLocalRandom.current().nextInt(0, 200)));
static String randomString(int len) {
String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
If you want to generate unique string. You can use java.util.UUID
import java.util.UUID;
String uuid = UUID.randomUUID().toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With