+ Reply to Thread
Results 1 to 2 of 2

Thread: Generate random string

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    5

    Generate random string

    Hi , i`d like to Generate random strings , what is the function for that ?

  2. #2
    Here is the function for that
    Code:
    import java.util.Random;
    
    public class RandomString
    {
    
      private static final char[] chars = new char[36];
    
      static {
        for (int idx = 0; idx < 10; ++idx)
          chars[idx] = (char) ('0' + idx);
        for (int idx = 10; idx < 36; ++idx)
          chars[idx] = (char) ('a' + idx - 10);
      }
    
      private final Random random = new Random();
    
      private final char[] buf;
    
      public RandomString(int length)
      {
        if (length < 1)
          throw new IllegalArgumentException("length < 1: " + length);
        buf = new char[length];
      }
    
      public String nextString()
      {
        for (int idx = 0; idx < buf.length; ++idx) 
          buf[idx] = chars[random.nextInt(chars.length)];
        return new String(buf);
      }
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts