Alex Haycock
Alex Haycock

Reputation: 395

How do you generate a string which has a user defined length?

I need to be able to generate strings with a user defined length. For example, if the user enters 128, I need a string with 128 characters. Any ideas on how to accomplish this?

Upvotes: 1

Views: 86

Answers (2)

obataku
obataku

Reputation: 29646

static final String generate(int n) {
  final char[] buf = new char[n];
  final Random rand = new Random();
  final int n_cs = Character.MAX_VALUE + 1;
  while (n > 0) {
    char ch;
    do {
      ch = (char) rand.nextInt(n_cs);
    } while (Character.isHighSurrogate(ch)
               || Character.isLowSurrogate(ch));
    buf[--n] = ch;
  }
  return new String(buf);
}

Generally, you should probably specify some sort of alphabet, as follows...

static final String generate(int n, final char[] alphabet) {
  final char[] buf = new char[n];
  final Random rand = new Random();
  final int n_alpha = alphabet.length;
  while (n > 0) {
    buf[--n] = alphabet[rand.nextInt(n_alpha)];
  }
  return new String(buf);
}

Upvotes: 1

IncrediApp
IncrediApp

Reputation: 10343

You can create X random chars (in a loop) and use a StringBuffer to concatenate them

Upvotes: 1

Related Questions