📜  在Java中生成给定大小的随机字符串

📅  最后修改于: 2022-05-13 01:55:41.162000             🧑  作者: Mango

在Java中生成给定大小的随机字符串

给定大小为 n,任务是生成此大小的随机字母数字字符串。

以下是生成给定大小的随机字母数字字符串的各种方法:

先决条件:在Java中生成随机数

  • 方法一:使用 Math.random()

    这里的函数getAlphaNumericString(n) 生成一个长度为字符串的随机数。这个数字是一个字符的索引,这个字符附加在临时局部变量 sb 中。最后 sb 被退回。

    // Java program generate a random AlphaNumeric String
    // using Math.random() method
      
    public class RandomString {
      
        // function to generate a random string of length n
        static String getAlphaNumericString(int n)
        {
      
            // chose a Character random from this String
            String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                        + "0123456789"
                                        + "abcdefghijklmnopqrstuvxyz";
      
            // create StringBuffer size of AlphaNumericString
            StringBuilder sb = new StringBuilder(n);
      
            for (int i = 0; i < n; i++) {
      
                // generate a random number between
                // 0 to AlphaNumericString variable length
                int index
                    = (int)(AlphaNumericString.length()
                            * Math.random());
      
                // add Character one by one in end of sb
                sb.append(AlphaNumericString
                              .charAt(index));
            }
      
            return sb.toString();
        }
      
        public static void main(String[] args)
        {
      
            // Get the size n
            int n = 20;
      
            // Get and display the alphanumeric string
            System.out.println(RandomString
                                   .getAlphaNumericString(n));
        }
    }
    
    输出:
    kU9vRVm9T1lFMbi3duO1
    

    方法二:使用 CharSet

    使用Java .nio.charset 包中的 Charset 随机生成 20 个字符长的字母数字字符串。

    1. 首先取 0 到 256 之间的 char 并遍历。
    2. 检查 char 是字母还是数字。
    3. 如果是,则在我们的字符串末尾添加
    4. 返回字符串

    下面是上述方法的实现:

    // Java program generate a random AlphaNumeric String
    // using CharSet method
      
    import java.util.*;
    import java.nio.charset.*;
      
    class RandomString {
      
        static String getAlphaNumericString(int n)
        {
      
            // length is bounded by 256 Character
            byte[] array = new byte[256];
            new Random().nextBytes(array);
      
            String randomString
                = new String(array, Charset.forName("UTF-8"));
      
            // Create a StringBuffer to store the result
            StringBuffer r = new StringBuffer();
      
            // Append first 20 alphanumeric characters
            // from the generated random String into the result
            for (int k = 0; k < randomString.length(); k++) {
      
                char ch = randomString.charAt(k);
      
                if (((ch >= 'a' && ch <= 'z')
                     || (ch >= 'A' && ch <= 'Z')
                     || (ch >= '0' && ch <= '9'))
                    && (n > 0)) {
      
                    r.append(ch);
                    n--;
                }
            }
      
            // return the resultant string
            return r.toString();
        }
      
        public static void main(String[] args)
        {
            // size of random alphanumeric string
            int n = 20;
      
            // Get and display the alphanumeric string
            System.out.println(getAlphaNumericString(n));
        }
    }
    
    输出:
    jj06CyZKfSBZQHM6KAUd
    
  • 方法 3:使用正则表达式
    1. 首先取 0 到 256 之间的字符。
    2. 删除除 0-9、az 和 AZ 之外的所有字符。
    3. 随机选择一个字符
    4. 最后添加我们需要的变量

    下面是上述方法的实现:

    // Java program generate a random AlphaNumeric String
    // using Regular Expressions method
      
    import java.util.*;
    import java.nio.charset.*;
      
    class RandomString {
      
        static String getAlphaNumericString(int n)
        {
      
            // length is bounded by 256 Character
            byte[] array = new byte[256];
            new Random().nextBytes(array);
      
            String randomString
                = new String(array, Charset.forName("UTF-8"));
      
            // Create a StringBuffer to store the result
            StringBuffer r = new StringBuffer();
      
            // remove all spacial char
            String  AlphaNumericString
                = randomString
                      .replaceAll("[^A-Za-z0-9]", "");
      
            // Append first 20 alphanumeric characters
            // from the generated random String into the result
            for (int k = 0; k < AlphaNumericString.length(); k++) {
      
                if (Character.isLetter(AlphaNumericString.charAt(k))
                        && (n > 0)
                    || Character.isDigit(AlphaNumericString.charAt(k))
                           && (n > 0)) {
      
                    r.append(AlphaNumericString.charAt(k));
                    n--;
                }
            }
      
            // return the resultant string
            return r.toString();
        }
      
        public static void main(String[] args)
        {
            // size of random alphanumeric string
            int n = 20;
      
            // Get and display the alphanumeric string
            System.out.println(getAlphaNumericString(n));
        }
    }
    
    输出:
    4J8pirLzX6oIF0IIIaUU
    
  • 方法四:生成大写字母/小写字母/数字的随机字符串

    当字母数字字符串中需要某些特定字符时,例如仅大写字母或小写字母或数字,请使用此方法。下面的示例生成大小为 n 的随机小写字母字符串。

    下面是上述方法的实现:

    // Java program generate a random
    // UpperCase or LowerCase or Number String
      
    import java.util.*;
      
    public class GFG {
      
        static String getAlphaNumericString(int n)
        {
      
            // lower limit for LowerCase Letters
            int lowerLimit = 97;
      
            // lower limit for LowerCase Letters
            int upperLimit = 122;
      
            Random random = new Random();
      
            // Create a StringBuffer to store the result
            StringBuffer r = new StringBuffer(n);
      
            for (int i = 0; i < n; i++) {
      
                // take a random value between 97 and 122
                int nextRandomChar = lowerLimit
                                     + (int)(random.nextFloat()
                                             * (upperLimit - lowerLimit + 1));
      
                // append a character at the end of bs
                r.append((char)nextRandomChar);
            }
      
            // return the resultant string
            return r.toString();
        }
      
        public static void main(String[] args)
        {
            // size of random alphanumeric string
            int n = 20;
      
            // Get and display the alphanumeric string
            System.out.println(getAlphaNumericString(n));
        }
    }
    
    输出:
    qbhalyuzrenuwgvqidno