Generating a random string

7 AM April 5, 2005

Here's a quick way to generate a short, random string in Java:


  Random r = new Random();

  String token = Long.toString(Math.abs(r.nextLong()), 36);

The resultant string is a maximum of ceil(ln(263) / ln(36)) = 13 characters long and is suitable for use as a temporary id or cookie name.

An even quicker and dirtier method is to simply convert a random double to a string:


  String token = "token" + Math.random();

This is useful in test cases and one-offs, but I wouldn't put it into production code.

By alang | # | Comments (12)
(Posted to javablogs and Java)

Comments

At 08:08, 05 Apr 2005 Florian wrote:

I do would apreciate it if you'd branch off a feed for stuff that's anything remotely python related, so the rest wouldn't clutter planetpython. But that's just my opinion, I'm sure many people like it a lot to read completely python unrelated stuff on planetpython.

(#)
At 08:52, 05 Apr 2005 Darren wrote:

I've been doing the following:

        Random random =  new Random();
        long r1 = random.nextLong();
        long r2 = random.nextLong();
        String hash1 = Long.toHexString(r1);
        String hash2 = Long.toHexString(r2);
        String hash = hash1 + hash2;

More verbose but the main differences are the length and the fact I create a Hex string.
I use this for cookies.

(#)
At 11:15, 05 Apr 2005 Alan Green wrote:

Florian, there's a python feed at:

http://cardboard.nu/feeds/blog_python.rdf.

Also, can you think of a concise way to do this in Python?

(#)
At 13:27, 06 Apr 2005 Cameron wrote:

Here's a way to do any length (passed in):

  String generate(int cch)
	{
	int    cb  = (cch + 3) / 4 * 3;     // base 64: 3 bytes = 4 chars
	byte[] ab  = new byte[cb];
	m_rnd.nextBytes(ab);                // session IDs should be random
	// encode the random bytes as a base-64 value of the desired length;
	// also: replace the special character '/' with the legal '$'
	return new String(Base64OutputStream.encode(ab), 0, cch).replace('/', '$');
	}

Peace.

(#)
At 10:23, 15 Feb 2006 rose wrote:

Hi
i need to know how to generate a random string with length 4 and characrters from A B C D E F ???thank uuuu

(#)
At 13:32, 29 Jun 2006 Nasete wrote:

On Python, random string, length 4, from characters A,B,C,D,E and F.

import random
string = ' '
for i in random.sample('ABCDEF',4):
    string+=i

probably there are shorter, smarter and more elegant ways.

(#)
At 11:54, 11 Aug 2006 Belto wrote:
 package test;
 import java.util.Random;
 public class Ran {
     public static void main(String st[]){
        String str=new  String("QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR");
 	StringBuffer sb=new StringBuffer();
 	Random r = new Random();
 	int te=0;
 	for(int i=1;i<=4;i++){
 		te=r.nextInt(62);
 		sb.append(str.charAt(te));
 	}
 	System.out.print(sb.toString());
     }
 }
(#)
At 02:43, 14 Aug 2006 Alan Green wrote:

Belto,

I still like my way better.

a

(#)
At 02:43, 13 Dec 2006 Lawrence wrote:

i need to know how to create a random string of names that does not duplicate any one name when randomized.

(#)
At 11:20, 26 Jul 2007 Nielz wrote:

Since this is the #1 result for python random string in Google, it might be worth mentioning that Nasete's snippet can be condensed to:

 import random
 string = ''.join(random.sample('ABCDEF', 4))
(#)
At 10:26, 15 Dec 2007 cy wrote:

Thats if every character should only be used once. If characters should be reused you could do it like this:

import random
string = ''
for i in range(4):
    string += random.choice('ABCDEF')
(#)
At 20:37, 07 Feb 2008 s wrote:
  ''.join([random.choice('ABCDEF') for x in xrange(4)])
(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green