C++

Random String Generator C++

Strings random generator can be one-of-a-kind. A random string generator is also known as a random character string generator when used in computer programming. It is very effective to generate random Strings, such as a Session-ID for a web application or a preliminary password after registering for an application.

To generate random characters, we should use the rand() method. It generates integer values at random. This number is created using an algorithm associated with the specific time it is called and returns a succession of seemingly unrelated numbers. There are some applications for generating random strings as follows:

  • Cryptography, which underpins most of the techniques that seek to offer security in modern communications, makes extensive use of unexpected random characters (e.g., encryption, authorization, electronic business, etc.).
  • Random characters are also utilized in instances where “fairness” can be simulated through randomization, such as jury selection and military draught lotteries.

Here’s the article that will generate the alphabet randomly with different scenarios in a simple way

Example 1: Using the rand() Function to Generate Random Alphabets in C++

The following C++ program generates a random string alphabet by using rand() function and srand() function. The rand() function generates the random alphabets in a string and srand() function is used to seed the rand() function.

Initially, we have a program that sets the array of alphabets size as “ch_Max,” which is of int char data type. After that, we constructed a string data type function represented as “RandomString” and passed an int variable “ch”. Inside the function, a character array is created as “alpha,” which has passed the character array size initialized above. The character array has 26 alphabets which are in lower case.

Then, we have created a variable as a “result” and currently kept this variable “result” empty. The for loop is cycled over the variable “ch” containing lowercase alphabets. Then, we have defined the variable “result”. The result has the rand() function for the character arrays of alphabets. This will generate a random alphabetic string.

Now, the program’s main function is invoked where the srand function is used to set the seed time as NULL for, and also the int variable “ch” is initialized with the value “15”. The random alphabet string generated will have 15 random alphabets from the given array.

#include <bits/stdc++.h>

using namespace std;
const int ch_MAX = 26;
string RandomString(int ch)
{
    char alpha[ch_MAX] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
                          'h', 'i', 'j', 'k', 'l', 'm', 'n',
                          'o', 'p', 'q', 'r', 's', 't', 'u',
                          'v', 'w', 'x', 'y', 'z' };
    string result = "";
    for (int i = 0; i<ch; i++)
        result = result + alpha[rand() % ch_MAX];

    return result;
}
int main()
{
   srand(time(NULL));
   int ch = 15;
   cout<<RandomString(ch) <<"\n";
   return 0;
}

The prompt shell displays the random alphabets string output as follows:

Example 2: Generating Alphabets String and Storing Them in the Array of Characters in C++

In this code, we first generate two arrays of characters, one for storing all of the alphabets and another for printing random characters. We chose a minimal length to keep things simple.

To start with the main function, we have declared an array of alphabets of size 26 as “Alphabets”. As there are 26 alphabets in general, these alphabets’ representation is in lowercase. Then, we have defined another character array as “RandString,” which has the size of “10”. The seed for the rand function is also set, bypassing the time to NULL values in the srand function.

We have a while loop for which the variable “k” is created and initialized with the value zero. The while loop runs through the size of the “RandString,” which is a random string and stores randomly created alphabets of string in a while loop. The variable “temp” is created here, which uses the rand function to generate a random string within a range of 26. The number is then passed to the alphabet array, generating a random string.

After that, we have a for loop for printing the alphabet string.

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
  char Alphabets[26] = {'a','b','c','d','e','f','g','h',
   'i','j','k','l','m','n','o','p','q',
   'r','s','t','u','v','w','x','y','z'};

  char RandString[10];
  srand(time(NULL));

  int k=0;
  while(k<10) {
    int temp = rand() % 26;
    RandString[k] = Alphabets[temp];
    k++;
  }

  for(k=0; k<10; k++)
    cout<<RandString[k];

  cout<<"\n";
  return 0;
}

The string has the random alphabetic character of length size 10, shown in the following shell.

Example 3: Generating Random Words String in C++

The above program has generated an alphabets string and stores them in the array. We are generating the string of random words in the following C++ program.

The program’s initial step has the void function created with the name “RandomWord,” which has passed a pointer character variable “StrWord”. Within the function, we have specified a variable as “len”. This variable uses the rand function to create a different value for characters inside the range of the array’s size.

Then, we have defined an array “StrWord,” which has the size of “len”. The while loop will iterate over the “StrWord” and generate the random word within the range of 26 characters. After that, the main function will print the random word through iteration by while loop.

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;
void RandomWord (char *StrWord)
{
  int len = rand () % 4 + 1;
  StrWord[len] = 0;
  while (len) StrWord [--len] = 'a' + rand () % 26;
}

int main ()
{
  char StrWord[5];
  char StrWord2[5];
  int i=0;
  srand(time(0));
  while (i<4)
  {
    RandomWord(StrWord);
    RandomWord(StrWord2);
    cout << "=>" << StrWord << ' ' << "=>" << StrWord2 << endl;
    i++;
  }
}

The outcome of the random words generator is displayed on the terminal shell.

Example 4: Generating Alpha-Numeric String in C++

Now, we will look at creating a random alphanumeric string in C++. We have lowercase letters, uppercase letters, and digits from 0 to 9. This program selects characters at random and then generates a random string.

At first, we have declared an array as “AlphaNumeric,” which contains both the lowercase and uppercase alphabets and the numeric value from 0 to 9. After that, the array size id is initialized using the sizeof function and stored in a newly created variable, “MyLen”.

Then, the function “RandomStr” is created for generating random alphanumeric strings within the range of array size. We have time set to zero within the main function, and the variable is defined as “l”. The user will enter the string length and then print on the shell.

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

static const char AlphaNumeric[] = "0123456789"
                                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                "abcdefghijklmnopqrstuvwxyz";
int MyLen = sizeof(AlphaNumeric) - 1;

char RandomStr() {
   return AlphaNumeric[rand() % MyLen];
}

int main() {
   srand(time(0));
   int l;
   cout << "Enter string length: ";
   cin>>l ;
   for(int m = 0; m < l; m++) {
      cout<<RandomStr();
   }
   cout<< "\n";
   return 0;
}

Thus, upon each code compilation, we got a different random alphanumeric string on the shell.

Conclusion

Random is among the most difficult concepts in C++ to explain. Even experienced programmers can be puzzled by multiple functions with the same name. However, using them appropriately can be enjoyable. We have seen in the above example how random alphabets, words, and even alphanumeric strings have been generated in the program C++. We have provided you with the simplest examples, which can be easily handled when dealing with random string generators in C++.
[/cc]

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content