java 在java中生成随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39222044/
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-11-03 04:11:45  来源:igfitidea点击:

Generate Random String in java

javastringrandomsecure-random

提问by Lucy

I'm trying to generate a string between capital A-Z in java using Secure Random. Currently I'm able to generate an alphanumeric string with special characters but I want a string with only upper case alphabets.

我正在尝试使用 Secure Random 在 java 中的大写 AZ 之间生成一个字符串。目前我能够生成一个带有特殊字符的字母数字字符串,但我想要一个只有大写字母的字符串。

  public String createRandomCode(int codeLength, String id){   
     char[] chars = id.toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new SecureRandom();
        for (int i = 0; i < codeLength; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        String output = sb.toString();
        System.out.println(output);
        return output ;
    } 

The input parameters are length of the output string & id whhich is alphanumeric string.Can't understand what modifications to make to the above code to generate only upper case alphabet string. Please help..

输入参数是输出字符串的长度和 id 是字母数字字符串。无法理解对上述代码进行哪些修改以仅生成大写字母字符串。请帮忙..

回答by DimaSan

Here is generator that I wrote and use:

这是我编写和使用的生成器:

public class RandomGenerator {
    private static final String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String generateRandom(int length) {
        Random random = new SecureRandom();
        if (length <= 0) {
            throw new IllegalArgumentException("String length must be a positive integer");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }

        return sb.toString();
    }
}

in numCharsstring you can put any characters you want to be included. int lengthparameter is the length of generated random string.

numChars字符串中,您可以放置​​要包含的任何字符。int length参数是生成的随机字符串的长度。

回答by shmosel

Your method randomly selects characters out of the idargument. If you want those to only be uppercase letters, then pass a string with those characters:

您的方法从id参数中随机选择字符。如果您希望它们只是大写字母,则传递一个包含这些字符的字符串:

String randomCode = createRandomCode(length, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

EDITIf you want to avoid duplicates, you can't just select characters at random. You'll want to shuffle them and pick out the first ncharacters:

编辑如果你想避免重复,你不能只是随机选择字符。你会想要洗牌并挑选出第一个n字符:

public String createRandomCode(int codeLength, String id) {   
    List<Character> temp = id.chars()
            .mapToObj(i -> (char)i)
            .collect(Collectors.toList());
    Collections.shuffle(temp, new SecureRandom());
    return temp.stream()
            .map(Object::toString)
            .limit(codeLength)
            .collect(Collectors.joining());
}

EDIT 2Just for fun, here's another way to implement the original random code generator (allowing duplicates):

编辑 2只是为了好玩,这是实现原始随机代码生成器的另一种方法(允许重复):

public static String createRandomCode(int codeLength, String id) {
    return new SecureRandom()
            .ints(codeLength, 0, id.length())
            .mapToObj(id::charAt)
            .map(Object::toString)
            .collect(Collectors.joining());
}

回答by Arnaud

Here is an example method that uses the int range for characters A to Z (also this method avoids duplicate characters in the String) :

这是一个示例方法,它使用字符 A 到 Z 的 int 范围(此方法也避免了 中的重复字符String):

public String createRandomCode(final int codeLength) {

    int min = 65;// A
    int max = 90;// Z


    StringBuilder sb = new StringBuilder();
    Random random = new SecureRandom();

    for (int i = 0; i < codeLength; i++) {

        Character c;

        do {

            c = (char) (random.nextInt((max - min) + 1) + min);

        } while (sb.indexOf(c.toString()) > -1);

        sb.append(c);
    }

    String output = sb.toString();
    System.out.println(output);
    return output;
}

The range part comes from this topic : Generating random integers in a specific range

范围部分来自这个主题:生成特定范围内的随机整数