Using Java 8 you can generate a random string of a-z characters using Random().ints(97, 123)
this works because the character a
is represented as 97
and z
is represented as 122
.
Then we can use .collect(...)
to convert the characters from random into a string.
Altogether the code looks like this:
int yourStringLength = 40;
String generatedString = new Random().ints(97, 123)
.limit(yourStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
And the resulting string would look a bit like this:
okphrralxtqywxgfnolloyiqfjlgputyzprpbwsr
If you want to also include spaces then simply start the .ints(...)
at 96 which is the ` character, and replace it with spaces once generated:
String generatedString = new Random().ints(97, 123)
.limit(yourStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
generatedString = generatedString.replaceAll("`", " ");
And the resulting string would look a bit like this:
ayowotibx sotvonazpm vjnyobdkzajfckutswu
If you want even more spaces to represent real word lengths then you can start the .ints(...)
even earlier or push out the top end, and replace the characters as required, for example for ints(96, 123)
also replace generatedString = generatedString.replaceAll("_", " ");
and the result would be like this:
hrqobe rufmcknwobzyh whaimaxgjsjg nyxcx