What is the most simple way? Minimizing any imports.
This one is good:
String str = Long.toHexString(Double.doubleToLongBits(Math.random()));
But it's not perfect, for example it complicates with custom length.
Also an option: How to make this String unique?
-
3Why don't you use string-handling functions? Just generate a random character in your desired range, in a loop, and keep concatenating it onto the string you're building. Also, why do you want to minimize imports?nanofarad– nanofarad2016年08月01日 14:40:06 +00:00Commented Aug 1, 2016 at 14:40
-
There are no prizes for minimizing imports. It doesn't affect the time it takes to run, or even really the time to compile.Daniel M.– Daniel M.2016年08月01日 14:43:28 +00:00Commented Aug 1, 2016 at 14:43
-
@hexafraction, yes, you are right, your method is rational. DanielM. thanks, I will notice that. But question is likely applied puzzle.San– San2016年08月01日 14:55:05 +00:00Commented Aug 1, 2016 at 14:55
2 Answers 2
Create a String of the characters which can be included in the string:
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Generate an integer using the Random class and use it to get a random character from the String.
Random random = new Random();
alphabet.charAt(random.nextInt(alphabet.length()));
Do this n times, where n is your custom length, and append the character to a String.
StringBuilder builder = new StringBuilder(n);
for (int i = 0; i < n; i++) {
builder.append(/* The generated character */);
}
Together, this could look like:
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public String generateString(int length) {
Random random = new Random();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
}
return builder.toString();
}
Sign up to request clarification or add additional context in comments.
Comments
RandomStringUtils from commons-lang. If you don't wish to import, check out its source.
nanofarad
41.6k4 gold badges97 silver badges133 bronze badges
answered Aug 1, 2016 at 14:45
David Soroko
9,3943 gold badges44 silver badges59 bronze badges
Comments
lang-java