在 Java 中生成字母数字随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18069434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:10:39  来源:igfitidea点击:

Generating Alphanumeric random string in Java

javastringrandomalphanumeric

提问by PrivusGuru

I am using String Builder from another answer, but I can't use anything but alpha/numeric, no whitespace, punctuation, etc. Can you explain how to limit the character set in this code? Also, how do I insure it is ALWAYS 30 characters long?

我正在使用另一个答案中的 String Builder,但我只能使用字母/数字,没有空格,标点符号等。您能解释一下如何限制此代码中的字符集吗?另外,我如何确保它总是 30 个字符长?

     Random generator = new Random();
    StringBuilder stringBuilder = new StringBuilder();
    int Length = 30;
    char tempChar ;
    for (int i = 0; i < Length; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        stringBuilder.append(tempChar);

I have looked at most of the other answers, and can't figure out a solution to this. Thanks. Don't yell at me if this is a duplicate. Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set.

我已经查看了大多数其他答案,但无法找到解决方案。谢谢。如果这是重复的,请不要对我大喊大叫。大多数答案都没有解释代码的哪一部分控制生成的数字的长度或调整字符集的位置。

I also tried stringBuilder.Replace(' ', '1'), which might have worked, but eclipse says there is no method for Replace for StringBuilder.

我也试过 stringBuilder.Replace(' ', '1'),这可能有用,但 eclipse 说没有方法替换 StringBuilder。

采纳答案by zapl

If you want to control the characterset and length take for example

如果要控制字符集和长度,例如

public static String randomString(char[] characterSet, int length) {
    Random random = new SecureRandom();
    char[] result = new char[length];
    for (int i = 0; i < result.length; i++) {
        // picks a random index out of character set > random character
        int randomCharIndex = random.nextInt(characterSet.length);
        result[i] = characterSet[randomCharIndex];
    }
    return new String(result);
}

and combine with

并结合

char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

to specify the characterset.

来指定字符集。

It's not based on StringBuildersince you know the length and don't need all the overhead.

它不是基于,StringBuilder因为您知道长度并且不需要所有开销。

It allocates a char[]array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.

它分配一个char[]正确大小的数组,然后用从输入数组中随机选择的字符填充该数组中的每个单元格。

more example use here: http://ideone.com/xvIZcd

更多示例在此处使用:http: //ideone.com/xvIZcd

回答by aroth

Here's what I use:

这是我使用的:

public static String randomStringOfLength(int length) {
    StringBuffer buffer = new StringBuffer();
    while (buffer.length() < length) {
        buffer.append(uuidString());
    }

    //this part controls the length of the returned string
    return buffer.substring(0, length);  
}


private static String uuidString() {
    return UUID.randomUUID().toString().replaceAll("-", "");
}

回答by Sello

You may try this:

你可以试试这个:

    //piece
    int i = 0;
    while(i < length){
      char temp =(char) (generator.nextInt(92)+32);
      if(Character.isLetterOrDigit(temp))
      {
        stringBuilder.append(temp);
        ++i;
      }
    }
    System.out.println(stringBuilder);

Should achieve your goal

应该达到你的目标