在Java中生成随机字符串,而不使用随机类或方法直接用于字符串

时间:2017-09-02 21:52:10

标签: java

我正在尝试写下代码,从预定义的字符串生成5个字符的随机字符串。

我的目标是创建一个长度为5的String数组,并将所有5个随机字符串存储在此数组中。

所以,我写下了以下代码:

public static String generateRandomString(int stringlength, String fullstring){
        //Generating random number which will use to pick character from provider string at index[i]
        int i =((int)(Math.random()*100));

        //Created a character array to store the characters picked up from provided String
        char [] randomString = new char[5];

        //Checking the condition if generated random number is greater than or equals to string length to avoid OutOfBoundException
        if (i>=stringlength){
            generateRandomString(stringlength, fullstring);
        }
        //Else Fetching the character from provided string and storing it into Char[]
        else
        {

                randomString [0] = (fullstring.charAt(i));
                randomString [1] = (fullstring.charAt(i));
                randomString [2] = (fullstring.charAt(i));
                randomString [3] = (fullstring.charAt(i));
                randomString [4] = (fullstring.charAt(i));
        }
        //Converting Char[] to String.
        String returnString = new String(randomString);

        //Returning String
        return returnString;

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //String Array to Store Random Strings
        String [] array = new String[5];

        //Provided String
        String fullstring = "abcdefghijklmnopqrstuvwxyz";
        int stringlength = fullstring.length();

        //Loop to store random strings into all indexes of String[]
        for(int j=0;j<5;j++){

        array[j]=generateRandomString(stringlength, fullstring);
        }

        //Printing Final String[]
        for(String var:array){
            System.out.println(var);
        }

    }

但我面临两个问题:

  1. 我希望我的随机字符串不包含单个字符,我当前的代码只为所有5个地方挑选一个字符。因为它取一个值(i)。我希望在char []为一个索引存储的每个字符后,将(i)的值再次更改为任何随机值。
  2. e.g。

    我得到&#34; aaaaa&#34;对于一个随机字符串但我想要&#34; auzje&#34;

    1. 当我打印Final String []时,有时我的输出中会出现NULL字符串。
    2. e.g。 &#34; &#34;

      &#34; AAAAA&#34;

      &#34; &#34;

      &#34; GGGGG&#34;

      &#34; IIIII&#34;

      我最终要找的是:

      &#34; ajsuh&#34;

      &#34; ldugj&#34;

      &#34; odueb&#34;

      &#34; mcnde&#34;

      &#34; yahnf&#34;

      请建议。

      非常感谢。

3 个答案:

答案 0 :(得分:1)

您可以更改

if (i>=stringlength){
    generateRandomString(stringlength, fullstring);
} else { // this is where you're saving all similar characters to the array
    randomString [0] = (fullstring.charAt(i));
    randomString [1] = (fullstring.charAt(i));
    randomString [2] = (fullstring.charAt(i));
    randomString [3] = (fullstring.charAt(i));
    randomString [4] = (fullstring.charAt(i));
}

randomString [0] = (fullstring.charAt((int)(Math.random()*100) % stringlength));
randomString [1] = (fullstring.charAt((int)(Math.random()*100) % stringlength));
randomString [2] = (fullstring.charAt((int)(Math.random()*100) % stringlength));
randomString [3] = (fullstring.charAt((int)(Math.random()*100) % stringlength));
randomString [4] = (fullstring.charAt((int)(Math.random()*100) % stringlength));

虽然可以进一步清理和抽象代码,但应从fullstringchar[]的不同索引中分配随机字符。

答案 1 :(得分:0)

您需要为每个输出符号生成一个新字符。假设您使用的是Java 8+,则可以从输入Stream生成fullstring个随机字符 - 将其限制为stringlength,然后收集到String;等,

public static String generateRandomString(int stringlength, String fullstring) {
    return Stream.generate(() -> Character.toString(fullstring.charAt( //
            (int) (Math.random() * fullstring.length())))) //
            .limit(stringlength).collect(Collectors.joining());
}

然后,在调用它时,再次生成随机的五个字符String(s)并将其限制为所需的五个String(s)并最终收集它。使用数组可能有点笨重,但可以像

一样实现
public static void main(String[] args) {
    String fullstring = "abcdefghijklmnopqrstuvwxyz";
    String[] r = Stream.generate(() -> generateRandomString(5, fullstring)) //
            .limit(5).collect(Collectors.toList()).toArray(new String[5]);
    System.out.println(Arrays.toString(r));
}

答案 2 :(得分:0)

一个简单但有点内存饥饿的方法是通过使用Random类或Math.random()

定义可接受字符的数组并选择索引。

示例:

String randomString(int length, char[] chars)
{
      char[] result = new char[length];
      Random rand = new Random();
      for(int x = 0; x < length; x++)
          result [x] = chars [Math.abs(rand.nextInt())%chars.length];
       return new String(result);
}