Replace all substring A in string s with substring B and use the custom strstr
# Include <iostream>
Using namespace STD;
Char * my_strstr (char * str1, const char * str2)
{
Assert (str1! = NULL & str2! = NULL );
Char * P = str1;
Const char * q = str2;
While (* str1! = '/0' & * str2! = '/0 ')
{
If (* str1 = * str2)
{
++ Str1;
++ Str2;
}
Else
{
Str1 = ++ P;
Str2 = Q;
}
}
If (* str2 = '/0 ')
{
Return P;
}
Return NULL;
}
Void str_a_to_ B (char * STR, const char * Suba, const char * subb)
{
Assert (STR! = NULL & Suba! = NULL & subb! = NULL );
Int Lena = strlen (Suba );
Int lenb = strlen (subb );
Char * P = STR;
While (P! = NULL)
{
P = my_strstr (STR, Suba );
If (P! = NULL)
{
If (Lena = lenb)
{
Strncpy (p, subb, Lena );
}
Else if (Lena> lenb)
{
Char * PTR = P + Lena;
Char * PS = P + lenb;
While (* PTR! = '/0 ')
{
* PS ++ = * PTR ++;
}
Strncpy (p, subb, lenb );
}
Else
{
Int newlen = strlen (STR );
Char * PTR = & STR [newlen-1];
Char * PS = P + Lena;
Int sp = lenb-Lena;
While (PTR> = ps)
{
* (PTR + SP) = * PTR;
-- PTR;
}
Strncpy (p, subb, lenb );
}
}
Else
{
Break;
}
P = my_strstr (STR + Lena, subb );
}
}
Int main ()
{
Char STR [200];
Memset (STR, 0,200 );
Strcpy (STR, "pqrstaaajkjk ");
Char CH = 'a ';
Cout <STR <Endl;
Char * Suba = "AA ";
Char * subb = "qqqqq ";
Str_a_to_ B (STR, Suba, subb );
Cout <STR <Endl;
System ("pause ");
Return 0;
}