Quantcast
Channel: How to generate a random alpha-numeric string - Stack Overflow
Viewing all articles
Browse latest Browse all 49

Answer by FileInputStream for How to generate a random alpha-numeric string?

$
0
0

I think this is the smallest solution here, or nearly one of the smallest:

 public String generateRandomString(int length) {
    String randomString = "";

    final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();
    final SecureRandom random = new SecureRandom();
    for (int i = 0; i < length; i++) {
        randomString = randomString + chars[random.nextInt(chars.length)];
    }

    return randomString;
}

The code works just fine. If you are using this method, i recommend you to use more than 10 characters. Collision happens at 5 characters / 30362 iterations. This took 9 seconds.


Viewing all articles
Browse latest Browse all 49

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>