Link to home
Start Free TrialLog in
Avatar of CodeLover
CodeLover

asked on

How to generate a random string

Hi, all

I am creating a web site with JSP. Could you please tell me how to generate a random string which consists of any number or any characters (1-9 or a-z or A-Z). Thanks.
Avatar of vemul
vemul

try this..

class Test6
{
     public static void main(String[] args)
     {
          String s = new String();
          int i = (int)(Math.random()*10) + 5;

          int rand = 0;
          for(int x = 0; x < i; x++)
          {
               rand = ((int)(Math.random()*10))%3;
               if( ( rand == 0))
                    s += (int)(Math.random()*10);
               else if(( rand == 1))
                    s += (char)(Math.random()*26 +65);
               else
                    s += (char)(Math.random()*26 +97);
          }

          System.out.println(s);
         
     }
}

This code guarantees that the length of the string is atleast 5; could contain 1-9, a-z, A-Z. It does not guarantee that every string that is generated will be unique though

HTH
vemul
sorry, a minor change... if u want numbers between 1-9 only,
change

s += (int)(Math.random()*10);
to
s += (int)(Math.random()*9 + 1);

vemul
Avatar of rrz
How long do you want the string to be? How about 40? Try this
import java.util.*;
class RandString{
public static void main(String[]args){
Random rand = new Random();
String [] charset = {"0","1","2","3","4","5","6","7","8","9",
                     "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                     "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};  // 62 elements
StringBuffer sb = new StringBuffer();
for(int n=0;n<40;n++){
                      sb = sb.append(charset[rand.nextInt(62)]);
}
System.out.println(sb.toString());
}
}
ASKER CERTIFIED SOLUTION
Avatar of yasser_helmy
yasser_helmy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Heres a class I once wrote for just that purpose:
-------------------------------------------------


import java.util.Random;

/**
 * This class can be used to generate strings of random characters.
 * The length of the generated strings, as well as the charactes the strings
 * are generated with can be specified
 *
 * @see java.util.Random
 * @author Jan Louwerens
 */
public class RandomString
{
   private static final String DEFAULT_SOURCE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

   private Random random = null;
   private String m_SourceChars = null;

   /**
    * Creates a RandomString instance with the source characters including
    * lowecase letters a-z, uppercase letters A-Z, and numbers 0-9
    */
   public RandomString()
   {
      this(DEFAULT_SOURCE_CHARS);
   }

   /**
    * Creates a RandomString instance with the specified source characters.
    * The sourceChars string must not be null and must contain at least one
    * character
    *
    * @param sourceChars a string of characters from which a random string
    *                    can be derived
    * @throws IllegalArgumentException if sourceChars is null or does not
    *                                  contain at least one character
    */
   public RandomString(String sourceChars)
      throws IllegalArgumentException
   {
      if (sourceChars == null)
         throw new IllegalArgumentException("sourceChars must not be null");

      if (sourceChars.length() <= 0)
         throw new IllegalArgumentException("sourceChars length must not be > 0");

      random = new Random();
      m_SourceChars = sourceChars;
   }

   /**
    * Returns a character chosen at random from the pool of sourceChars
    *
    * @return a character chosen at random from the pool of sourceChars
    */
   public char nextChar()
   {
      int index = random.nextInt(m_SourceChars.length());
      return m_SourceChars.charAt(index);
   }

   /**
    * Returns a string of the specified length whose characters are chosen
    * at random from the pool of sourceChars
    *
    * @param length the length of the generated string. must be >= 0
    * @return a string of the specified length whose characters are chosen
    *         at random from the pool of sourceChars
    * @throws IllegalArgumentException if length < 0
    */
   public String nextString(int length)
      throws IllegalArgumentException
   {
      if (length < 0)
         throw new IllegalArgumentException("length must be >= 0");

      StringBuffer results = new StringBuffer(length);
      for (int index = 0; index < length; index++)
         results.append(nextChar());

      return results.toString();
   }

   /**
    * Returns a character chosen at random from the pool of sourceChars<br>
    * NOTE: If you wish to generate multiple characters, it is suggested
    *       that you create a RandomString instance and use the nextChar()
    *       method
    *
    * @return a character chosen at random from the pool of sourceChars
    * @see RandomString()
    * @see nextChar()
    */
   public static char getRandomChar()
   {
      return getRandomChar(DEFAULT_SOURCE_CHARS);
   }

   /**
    * Returns a character chosen at random from the pool of sourceChars<br>
    * NOTE: If you wish to generate multiple characters, it is suggested
    *       that you create a RandomString instance and use the nextChar(String)
    *       method
    *
    * @param sourceChars a string of characters from which a random character
    *                    can be chosen
    * @return a character chosen at random from the pool of sourceChars
    * @see RandomString(String)
    * @see nextChar(String)
    */
   public static char getRandomChar(String sourceChars)
   {
      RandomString randomString = new RandomString(sourceChars);
      return randomString.nextChar();
   }

   /**
    * Returns a string of the specified length whose characters are chosen
    * at random from the pool of sourceChars<br>
    * NOTE: If you wish to generate multiple strings, it is suggested
    *       that you create a RandomString instance and use the nextString(int)
    *       method
    *
    * @param length the length of the generated string. must be >= 0
    * @return a string of the specified length whose characters are chosen
    *         at random from the pool of sourceChars
    * @throws IllegalArgumentException if length < 0
    * @see RandomString()
    * @see nextString(int)
    */
   public static String getRandomString(int length)
      throws IllegalArgumentException
   {
      return getRandomString(DEFAULT_SOURCE_CHARS, length);
   }

   /**
    * Returns a string of the specified length whose characters are chosen
    * at random from the pool of sourceChars<br>
    * NOTE: If you wish to generate multiple strings, it is suggested
    *       that you create a RandomString instance and use the
    *       nextString(String, int) method
    *
    * @param sourceChars a string of characters from which a random string
    *                    can be derived
    * @param length the length of the generated string. must be >= 0
    * @return a string of the specified length whose characters are chosen
    *         at random from the pool of sourceChars
    * @throws IllegalArgumentException if sourceChars is null or does not
    *                                  contain at least one character, or
    *                                  if length < 0
    * @see RandomString(String)
    * @see nextString(int)
    */
   public static String getRandomString(String sourceChars, int length)
      throws IllegalArgumentException
   {
      RandomString randomString = new RandomString(sourceChars);
      return randomString.nextString(length);
   }
}

yasser_helmy,
er, that not the way u use stringbuffer right? :P
sorry..
replace 's+=' by 's.append()'..
i think the output string will be totally random.. hope it helps.. :)
Avatar of CodeLover

ASKER

Hi, all

Most of the codes work well. I think yasser's code is the best. Thanks all.
hi codelover.. i hope i helped you well..
everybody.. thanx for the new great ideas i got from you..
:)
try this,


public class Random
{
      public static String nextString()
      {
          StringBuffer message = new StringBuffer();
          message.append( random.nextInt(1024) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( random.nextInt(1024) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( random.nextInt(1024) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( random.nextInt(1024) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );
          message.append( (char) ( random.nextInt( 26 ) + 65 ) );

          return message.toString();
      }
}