Open In App

How to Create a Random Alpha-Numeric String in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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

  1. Define a constant string CHARACTERS that contains all the possible characters that can be included in the random string.
  2. Create a random number generator using the random_device and mt19937 classes from the <random> library.
  3. Create a uniform integer distribution that ranges from 0 to the size of CHARACTERS minus 1.
  4. Initialize an empty string random_string. Then, in a loop that runs length times, append a randomly selected character from CHARACTERS to random_string.
  5. 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++
// 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)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads