Viết hàm tìm và thay thế một chuỗi con trong chuỗi cho trước
Ex:
Input:
Nguyen Van A
A
B
Output: Nguyen Van B
Code:
#include <bits/stdc++.h>
using namespace std;
int Count_string(char *s = new char[1000],char * temp = new char[1000])
{
char a[100000];
int x=0,f=0,g=0,count=-1,gg=0;
for(int i = 0 ; i < strlen(s) ; i++)
{
if(f == 0 && *(s+i) != ' ')
f = 1;
if(f != 0)
{
if(*(s+i) == ' ')
g++;
if(g <= 1)
{
a[x++] = *(s+i);
if(*(s+i+1) != ' ')
g=0;
if(*(s+i) == ' ')
{
count++;
int j = 0;
for(int i = 0 ; i < strlen(temp) ; i++)
{
if(*(a+i) == *(temp+i))
j++;
if(*(a+i) != *(temp+i))
j--;
}
if(j == strlen(temp))
{
return gg;
break;
}
x = 0;
}
}
if(g > 1 && *(s+i+1) != ' ')
g = 0;
}
gg++;
}
if(gg == strlen(s))
count++;
return gg;
}
void Delete(char *s = new char[100],char *t = new char[100])
{
int a[100000],x=0;
for(int i = 0 ; i < strlen(t) ; i++)
a[x++] =(int)*(t+i);
int b[100000],y=0,f=0,c[100000],z=0;
for(int i = 0 ; i < strlen(s) ; i++)
{
if(*(s+i) != ' ')
b[y++] = (int)*(s+i);
if(*(s+i) == ' ')
{
b[y++] = (int)*(s+i);
int k=0;
for(int i = 0 ; i < x ; i++)
{
if(a[i] == b[i])
k++;
}
if(k < x)
{
for(int i = 0 ; i < y ; i++)
c[z++] = b[i];
y = 0;
}
if(k == x)
y = 0;
}
f++;
}
if(f == strlen(s))
{
int k=0;
for(int i = 0 ; i < x ; i++)
{
if(a[i] == b[i])
k++;
}
if(k < x)
{
for(int i = 0 ; i < y ; i++)
c[z++] = b[i];
y = 0;
}
if(k == x)
y = 0;
}
for(int i = 0 ; i < z ; i++)
cout<<(char)c[i];
}
int Compare(char *s = new char[1000] , char *r = new char[1000])
{
int j = 0;
for(int i = 0 ; i < strlen(s) ; i++)
{
if(*(s+i) == *(r+i))
j++;
if(*(s+i) != *(r+i))
j--;
}
if(j == strlen(r))
return 1;
return 0;
}
void Insert_string(int f , char *s = new char[1000] ,char *r = new char[1000],char *memory = new char[1000])
{
int c[100000],z=0,k = f-1;
for(int i = 0 ; i < strlen(s) ; i++)
{
if(k == i)
{
if(k != 0)
{
c[z++] = (int)' ';
for(int i = 0 ; i < strlen(r) ; i++)
c[z++] = (int)*(r+i);
c[z++] = (int)' ';
}
if(k == 0)
{
for(int i = 0 ; i < strlen(r) ; i++)
c[z++] = (int)*(r+i);
c[z++] = (int)' ';
}
}
if(k != i || k == 0)
c[z++] = (int)*(s+i);
}
if(k >= strlen(s))
{
c[z++] = (int)' ';
for(int i = 0 ; i < strlen(r) ; i++)
c[z++] = (int)*(r+i);
}
for(int i = 0 ; i < z ; i++)
*(memory+i) = (char)c[i];
//for(int i = 0 ; i < z ; i++)
//cout<<(char)c[i];
}
//void replace(chuoi , chuoi old , chuoi new)
void replace(char *s = new char[1000],char *t = new char[1000],char *r = new char[1000],char * temp = new char[1000],char *memory = new char[1000])
{
int k = Count_string(s,t)+1;
Insert_string(k,s,r,memory);
Delete(memory,t);
};
int main()
{
char *s = new char[1000],*t = new char[1000],*r = new char[1000],*temp = new char[1000],*memory = new char[1000];
cout<<"Nhap chuoi: ";
gets(s);
fflush(stdin);
cout<<"Chuoi con cu: ";
gets(t);
fflush(stdin);
cout<<"Chuoi con moi: ";
gets(r);
fflush(stdin);
cout<<"Chuoi moi thay doi: ";
replace(s,t,r,temp,memory);
return 0;
}