Create a Random Alpha-Numeric String in C++
To generate a random alpha-numeric string in C++, we use a random number generator along with the string that contains all the characters and numbers. We can pick a random index for each character in the alphanumeric string of the given size.
Approach
- Define a constant string
CHARACTERS
that contains all the possible characters that can be included in the random string. - Create a random number generator using the
random_device
andmt19937
classes from the<random>
library. - Create a uniform integer distribution that ranges from 0 to the size of
CHARACTERS
minus 1. - Initialize an empty string
random_string
. Then, in a loop that runslength
times, append a randomly selected character fromCHARACTERS
torandom_string
. - Return
random_string
.
C++ Program to Create a Random Alpha-Numeric String
The following program illustrates how to create a random alpha-numeric string in C++.
// C++ Program to illustrate how to create a random
// alpha-numeric string
#include <iostream>
#include <random>
#include <string>
using namespace std;
string generateRandomString(int length)
{
// Define the list of possible characters
const string CHARACTERS
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"
"wxyz0123456789";
// Create a random number generator
random_device rd;
mt19937 generator(rd());
// Create a distribution to uniformly select from all
// characters
uniform_int_distribution<> distribution(
0, CHARACTERS.size() - 1);
// Generate the random string
string random_string;
for (int i = 0; i < length; ++i) {
random_string
+= CHARACTERS[distribution(generator)];
}
return random_string;
}
int main()
{
int length = 10;
string random_string = generateRandomString(length);
cout << "Random String: " << random_string << endl;
return 0;
}
Output
Random String: ihoSqnkXRz
Time Complexity: O(N), here N is the length of the string.
Auxiliary Space: O(1)
How to Create a Random Alpha-Numeric String in C++?
Creating a random alpha-numeric string in C++ means generating random characters from the set of alphanumeric characters (i.e., ‘A’-‘Z’, ‘a’-‘z’, and ‘0’-‘9’) and appending them to a string. In this article, we will learn how to create a random alpha-numeric string in C++.
Example
Output:
a8shg1la