6

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

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
junaidp
  • 10,801
  • 29
  • 89
  • 137

5 Answers5

9

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)));
}
Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53
7

If you're happy to use third-party libraries, you may find the RandomStringUtils class from Apache Commons Lang helpful.

You can specify the allowed set of characters (or use all available characters).

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
2
import java.util.*;

class Test {

  static Random r = new Random();

  static char[] choices = ("abcdefghijklmnopqrstuvwxyz" +
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
      "01234567890" +
      "$#_").toCharArray();

  public static String getSalt(int len) {
    StringBuilder salt = new StringBuilder(len);
    for (int i = 0; i<len; ++i)
      salt.append(choices[r.nextInt(choices.length)]);
    return salt.toString();
  }

  public static void main(String[]_) {
    System.out.println(getSalt(32));
  }
}

Example output: vdq5L6bANFIQH_MUyKyZxLcOkJeB3uJ1

Vlad
  • 18,195
  • 4
  • 41
  • 71
2

If you want to generate this http://en.wikipedia.org/wiki/Special_characters special characters then try this

char c = (char) (randomGenerator.nextInt(0xB4 - 21 + 1) + 21);
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1
String alphabet = "here specify all the characters you want";
    final int N = alphabet.length();

    Random r = new Random();
    String finalStr= "";

    for (int i = 0; i < 50; i++) {
       finalStr+=alphabet.charAt(r.nextInt(N));
    }
PSR
  • 39,804
  • 41
  • 111
  • 151