Answer to Question #157326 in C++ for Abdul Rehman

Question #157326

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: abcdefabcdkuiy


1
Expert's answer
2021-01-21T13:27:29-0500
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char str[200], pat[100], rpat[100];
    cout << "Str: ";
    cin >> str;
    cout << "Pat: ";
    cin >> pat;
    cout << "Rpat: ";
    cin >> rpat;
    int count = 0;
    int pos[200]; // positions of pat in str
    pos[0] = -strlen(pat); // dummy value for first iteration
    char *from = str;

    while ((from = strstr(from, pat)) != NULL) {
        count++;
        pos[count] = from - str; // save all occurrences of pat
        from += strlen(pat);
    }

    if (count == 0) {
        cout << "Pat not found\n";
    }
    else {
        char result[200];
        int strPos = 0; // current position to copy in str
        int resPos = 0; // end position of result to append to
        for (int i = 1; i <= count; i++) {
            int rawLen = pos[i] - pos[i - 1] - strlen(pat); // length of str before occurrence of pat
            memcpy(result + resPos, str + strPos, rawLen); // append part of str
            resPos += rawLen;
            memcpy(result + resPos, rpat, strlen(rpat)); // append rpat instead of pat
            resPos += strlen(rpat);
            strPos += rawLen + strlen(pat);
        }
        int rawLen = strlen(str) - pos[count] - strlen(pat); // one more step, if str doess not finish with pat
        memcpy(result + resPos, str + strPos, rawLen);
        result[resPos + rawLen] = '\0';

        strcpy(str, result);
        cout << "After replace:\n";
    }
    cout << "Str: " << str;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog