# Create a random string with a set prefix [closed]

Posted on

Problem

I was curious on how I could create a random string and have it have a set prefix. Lets say, as an example, 3456. This question is more referring to how I would join two strings together, my prefix and my random string.

To give a more comprehensive exmaple of what i’m looking for, let’s say I generate the string “ab8897fjs”. I would like to add my prefix to that string to make it “3456ab8897fjs”.

Thank you!

Add: This is my code for string generation.

``````char *randstring(size_t length) {

static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
char *randomString = NULL;

if (length) {
randomString = malloc(sizeof(char) * (length +1));

if (randomString) {
for (int n = 0;n < length;n++) {
int key = rand() % (int)(sizeof(charset) -1);
randomString[n] = charset[key];
}

randomString[length] = '';
}
}

return randomString;
}
``````

Solution

When you do `rand()%n` you will get a random number in the range [0, n-1] but the distribution will not be uniform. Some values will be more likely than others. This is more easily illustrated if we drop the number of random bits from 32 to 4, i.e. `RAND_MAX=15`. And we want a number between 0 and 10 so we do `rand()%11`. Now for returns values of 0-10 from `rand()` well get the wanted values, but what about the rest of the range? Well from 11 to `RAND_MAX` well also get 0-4… This means that values 0-4 are twice as likely to occur as values 5-10, this isn’t what we wanted!

I explain this in another answer here: https://codereview.stackexchange.com/a/159760/36120