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

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

$
0
0
public static String RandomAlphanum(int length)
    {
        String charstring = "abcdefghijklmnopqrstuvwxyz0123456789";
        String randalphanum = "";
        double randroll;
        String randchar;
        for
        (double i = 0; i < length; i++)
        {
            randroll = Math.random();
            randchar = "";
            for
            (int j = 1; j <= 35; j++)
            {
                if
                (randroll <= (1.0 / 36.0 * j))
                {
                    randchar = Character.toString(charstring.charAt(j - 1));
                    break;
                }
            }
            randalphanum += randchar;
        }
        return randalphanum;
    }

I used a very primitive algorithm using Math.random(). To increase randomness, you can directly implement the util.Date class. Nevertheless, it works.


Viewing all articles
Browse latest Browse all 49

Trending Articles



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