Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unique string within specific length range

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:

  1. No additional libraries (Google Guava or Apache Common)
  2. JDK 1.6 only

Many thanks to your contribution!

like image 345
Malakai Avatar asked Aug 06 '26 19:08

Malakai


1 Answers

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();
like image 111
Naghaveer R Avatar answered Aug 08 '26 09:08

Naghaveer R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!