Write a C++ program in which, read three c-string str, pat and rpat from user. Now your task is to find pat in str, replace pat with rpat in str if pat is found else display a message pat not found. Example 1 Example 2 Example 3 Example 4 Input: Str: abcdefabcdkuiyh Pat: abcd Rpat: xyz Output: After replace: Str: xyzefxyzkuiyh Input: Str: abcdefabcdkuiyh Pat: ab Rpat: xyz Output: After replace: Str: xyzcdefxyzcdkuiyh Input: Str: abcdefabcdkuiyh Pat: abc Rpat: xyz Output: After replace: Str: xyzdefxyzdkuiyh Input: Str: abcdefabcdkuiyh Pat: abcdefg Rpat: xyz Output: Pat not found Str: abcdefabcdkuiyh
#include <iostream>
#include <cstring>
#define MAXLENGTH 2555
using namespace std;
int main() {
char *str = new char[MAXLENGTH];
char *pat = new char[MAXLENGTH];
char *rpat = new char[MAXLENGTH];
//read all necessary data
cout << "Input:" << endl << "Str:";
cin.getline(str, MAXLENGTH);
cout << "Pat:";
cin.getline(pat, MAXLENGTH);
cout << "Rpat:";
cin.getline(rpat, MAXLENGTH);
char *pch; //substring starting from pat
bool checkPat = false; //check whether pat is in the string
while (true) {
pch = strstr(str, pat);
if (pch == NULL) //if pat is not found
break;
else {
//shift part of the string after pat occurrence
char *leftover = pch + strlen(pat);
char *copy = new char[MAXLENGTH];
strncpy(copy, leftover, strlen(leftover));
char *rightover = pch + strlen(rpat);
strncpy(rightover, copy, strlen(leftover));
//change pat to rpat
strncpy(pch, rpat, strlen(rpat));
//put null symbol to fix problem of c copy
if (strlen(rpat) < strlen(pat))
pch[strlen(pch) + strlen(pat) - strlen(rpat) - 2] = 0;
checkPat = true;
}
}
//Printing output
cout << "Output:\n";
if (checkPat)
cout << "After replace:\nStr: " << str;
else
cout << "Pat not found\nStr: " << str;
return 0;
}
Comments
Leave a comment