Java Random Int randomStr(int length, String charSet)

Here you can find the source of randomStr(int length, String charSet)

Description

Generates random alphanumeric String of the specified length using characters specified in charSet.

License

Apache License

Parameter

Parameter Description
length a parameter
charSet character set

Declaration

public static String randomStr(int length, String charSet) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from w w w.j  a  v  a  2s.  c  om
     * Generates random alphanumeric String of the specified length using characters specified in charSet.
     * 
     * @param length
     * @param charSet character set 
     */
    public static String randomStr(int length, String charSet) {
        char[] result = new char[length];
        fillWithRandomChars(result, charSet);
        return new String(result);
    }

    /**
     * Populates given char array with random string using characters from
     * specified character set. Can be used for memory conservation purposes.
     * 
     * @param str
     * @param charSet  
     */
    public static void fillWithRandomChars(char[] str, String charSet) {
        char[] ALPHA_NUM = charSet.toCharArray();
        for (int i = 0; i < str.length; i++) {
            str[i] = ALPHA_NUM[(int) (Math.random() * ALPHA_NUM.length)];
        }
    }
}

Related

  1. randomQuickSort(int[] array)
  2. randomRange(int min, int max)
  3. randomSize(int maxValue)
  4. randomSMSCode(int length)
  5. randomStr(int length)
  6. randomString(int count)
  7. randomString(int length)
  8. randomString(int length)
  9. randomString(int length)