logo

How to generate random strings from a set of characters in C

#include <stdio.h> #include <stdlib.h> #include <time.h> void rand_string(char* str, int num) { for (int i = 0; i < num; i++) { str[i] = rand() % ('z' - 'a' + 1) + 'a'; } str[num] = 0; } char random_characters[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '+', '=', '-' }; int random_characters_length = sizeof(random_characters) / sizeof(char); void rand_string_2(char* str, int num) { for (int i = 0; i < num; i++) { str[i] = random_characters[rand() % random_characters_length]; } str[num] = 0; } int main(int argc, char* argv[]) { srand(time(NULL)); char str[16]; rand_string_2(str, 15); printf("%s\n\n", str); return 0; }