简体   繁体   中英

Creating a random string with only certain letters and a certain length

So I want to generate a random string but only want certain characters to be the string (Only ones that can be used in a file name to be hosted so something like www.example.com/HERE.EXTENTION).

So how can I make a random string that is a length that I want with only certain letters I want.

I know I can do a for look from the length, and then use the random number and cast that to a char and add it to a string. But I don't want characters that I don't want to be added and going through a loop with all that I don't want because that would take too long.

Use this quick method:

String genRand(int length){
   Random rand=new Random();
   String possibleLetters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.";   
   StringBuilder sb = new StringBuilder(length);
   for(int i = 0; i < length; i++) 
      sb.append(possibleLetters.charAt(rand.nextInt(possibleLetters.length())));
   return sb.toString();
}

Edit possibleLetters to include the characters you want. Note that \\ and newlines must be escaped.

Store all your accepted letters in an array, then generate a random number between 0 and the length of this array N times, to get N indices of a letter in the array. Concatenate the letters.

EDIT:

Note that if your goal is to generate unique names, random is not the solution. A random doesn't guarantee uniqueness.

Other than the two answers -

You can have it like <yourChoiceOfName>-<currentTime>.yourext . This way the chances of two files with the same name is lesser.

The currenttime could include milliseconds .

In this case you have a known length ie length of yourChoiceOfName + length of currentTime + lenght of yourext .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM