Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number generator for special characters [duplicate]

Tags:

java

I am trying to generate random number with special characters

what i do for simple integers is

Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt();

what can i do to get some thing like this in my random numbers

String salt = "Random$SaltValue#WithSpecialCharacters12@$@4&#%^$*";

thanks

like image 984
junaidp Avatar asked Nov 30 '22 12:11

junaidp


1 Answers

You can try the following:

  • Init your special characters set.
  • Create a StringBuilder to contain your desired string.
  • Get random character and append to StringBuilder object.

The code:

final String alphabet = "<Your special characters>";
final int N = alphabet.length();
Random rd = new Random();
int iLength = <length you want>;
StringBuilder sb = new StringBuilder(iLength);
for (int i = 0; i < iLength; i++) {
    sb.append(alphabet.charAt(rd.nextInt(N)));
}
like image 119
Rong Nguyen Avatar answered Dec 25 '22 10:12

Rong Nguyen