Jump to content

[C++] Inlocuirea unui subsir dintr-un sir


M1H41
 Share

Recommended Posts

Pentru a inlocui un subsir cu un altul trebuie parcurse urmatoarele etape:

-se cauta subsirul pe care dorim sa il inlocuim in sirul principal

-se sterge subsirul respectiv

-se insereaza in sirul principal subsirul pe care dorim sa il adaugam in pozitia in care a fost gasit subsirul initial

Algortimul aici:

#include <iostream>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

using namespace std;

int main()
{
    char sir[256], sb[30], s[30], aux[256], *p;
    cout<<"Sirul este:"<<endl;
    cin.get(sir, 256);
    cin.get();
    cout<<"Se va inlocui subsirul:"<<endl;
    cin.get(sb, 30);
    cout<<"Cu subsirul:"<<endl;

    cin.get();
    cin.get(s, 30);
    p=strstr(sir,sb);
    while(p){
        strcpy(p, p+strlen(sb));
        strcpy(aux, p);
        strcpy(p,s);
        strcpy(p+strlen(s), aux);
        p=strstr(p+1, sb);
    }
    cout<<"Sirul este:"<<endl<<sir;
 return 0; }

Link to comment
Share on other sites

E mai mult C decat C++,

string sir, subsir, replace;
	
cout << "Sirul este:" << endl;
getline( cin, sir );
cout << "Se va inlocui subsirul:" << endl;
getline( cin, subsir );
cout << "Cu subsirul:" << endl;
getline( cin, replace );

while( sir.find( subsir ) != string::npos )
    sir.replace( sir.find( subsir ), subsir.size( ), replace );

cout << "Sirul este:" << endl << sir;

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.