Java 中的字符串生成器

String generator in Java

我需要生成随机字母数字字符串(5 或 6 个字符)以便将其放入特定字段。 谁能给我提供解决方案? 已尝试堆栈上其他帖子中描述的几种方法但没有成功。

尝试过类似的东西:

public static String generateString(Random rng, String characters, int length)
{
    char[] text = new char[length];
    for (int i = 0; i < length; i++)
    {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

但不知道为什么将随机作为参数传递,以及在调用方法时我应该为它提供什么

既然你像你说的那样尝试了很多次,我可以帮助你找到最简单的解决方案之一-

  1. Have a string declared with characters of your choice. e.g. 0..9..a..z..A..Z
  2. Have a loop with the number of characters you would like to generate. e.g. if you want 5 random characters, you would have something like for(int i = 0; i < 5; i++)
  3. For each iteration, pick a random character from step 1 using the length of the string you have in step 1.

这是一个示例代码:

private static final char[] VALID_CHARACTERS =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456879".toCharArray();

public static String getRandomString( final int length ) {
    // Check input
    if( length <= 0 ) {
        return "";
    }
    // Generate string
    Random rand = new Random();
    char[] buffer = new char[length];
    for( int i = 0; i < length; ++i ) {
        buffer[i] = VALID_CHARACTERS[rand.nextInt( VALID_CHARACTERS.length )];
    }
    //
    return new String( buffer );
}

这个简单的方法使用有效字符常量,每次从中随机轮询一个字符以构建所需长度的字符串。

例如,要获取 10 个字符的字母数字字符串,您可以这样调用方法:

getRandomString( 10 );