Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

BuildRandomStr (): accept as parameters: the source string and an integer n; fro

ID: 3826944 • Letter: B

Question

BuildRandomStr (): accept as parameters: the source string and an integer n; from the source string, randomly choose n characters and build a new string with them; return the new string and make the changes to the original string available to the calling interface. removeRandom (): accept as a parameter: the string to be edited; remove, at random, one character from that string and return it; changes to the string must be made in-place Use these functions to create a program that: Prompts the user to enter: a string to be edited a number of characters to be extracted from the string Aborts the program with an appropriate error message if: the user input string contains less than 5 characters the number of characters is not a positive number less than the number of characters the string Prints: the original string the newly-built string of randomly chosen characters the characters remaining from the original string (Inputs will be shaded. Bold outputs must change depending on the input.)

Explanation / Answer

#include<iostream>
#include<cstdlib>
#include<cctype>
#include<ctime>

#include<string>

using namespace std;

char removeRandom(string& str) {
   srand (time(NULL)); //initialize random number generator
   unsigned int len = str.length();
   int random = rand()%(int)len;
   char ch = str[random];
   str.erase(random,1);
   return ch;
}

string buildRandomStr(string& str, int n) {
   string randomStr = "";
   char ch;
   for (int i =0; i<n; i++) {
       ch = removeRandom(str);
       randomStr = randomStr + ch;
       if (!isalpha(ch)) //ignores charecters those are not alphabets such as blank space and numbers<WARNING>
           i--;
   }
   return randomStr;
}

int main() {
   string str, rndStr;
   int n;
   cout<<"Enter a string:"<<endl;
   getline(cin, str);
   cout<<"How many characters should be extracted?"<<endl;
   cin>>n;
  
   rndStr = buildRandomStr(str,n);

   cout<<"New String: "<<rndStr<<endl;
   cout<<"Leftover Characters: " << str << endl;
}

I kept the code as simple as possible. I have commented few lines to remove confusion. I hope you liked the code. If incase you face any trouble with the code, please feel free to comment below. I shall be glad to help you with the code.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote