1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#include <iostream>
using namespace std;
void strReplaceSubStr(char [], char [], char [], char []);
int main()
{
//declaring and initializing req. variables
const int size = 50;
char myString_1[size], myString_2[size];
char myString_3[size];
char thenewString[50];
//getting input (a string) from the user
cout << "\n\t[*] Type a string/sentence: ";
cin.getline(myString_1,size);
cout << "\t[*] Enter the substring that you want to find: ";
cin >> myString_2;
cout << "\t[*] Enter the substring that you want to replace with: ";
cin >> myString_3;
strReplaceSubStr(myString_1,myString_2,myString_3,thenewString);
cout << "\n\t\t[!] Replaced string: " << thenewString << endl << endl;
system("pause");
return 0;
}
void strFindindex(char myString_1[], char myString_2[],int indices[],int &count)
{
int k,found;
count=0;
for(int i=0; myString_1[i] != '\0'; i++) {
k=i;
found = 1;
for(int j=0; myString_2[j] != '\0'; j++) {
if(myString_2[j] != myString_1[k])
found = 0;
k++;
}
if(found) {
indices[count] = i;
count++;
}
}
}
//it will calculate and return the length of the string
int lengthOf(char myString_1[])
{
int count;
for(count=0; myString_1[count] != '\0'; count++);
return count;
}
//will append a string to another string
void append(char newString[],char myString_3[],int &pos)
{
for(int i=0; myString_3[i] != '\0'; i++) {
newString[pos] = myString_3[i];
pos++;
}
}
//this function will replace a substring with another string
void strReplaceSubStr(char myString_1[], char myString_2[], char myString_3[], char newString[])
{
int indices[50];
int isize,inum=0,pos=0;
//will stores indices in "indices" array
strFindindex(myString_1,myString_2,indices,isize);
int length = lengthOf(myString_3);
int length2 = lengthOf(myString_2);
for(int i=0; myString_1[i] != '\0'; i++) {
if(i == indices[inum]) {
//myString_3 will be appended in newString
append(newString,myString_3,pos);
inum++;
i = i+length2-1;
}
else {
newString[pos] = myString_1[i];
pos++;
}
}
newString[pos] = '\0';
}
|