A string replacement problem

Replace all occurrence of the given pattern to ‘X’.
For example, given that the pattern=”abc”, replace “abcdeffdfegabcabc” with “XdeffdfegX”. Note that multiple occurrences of abc’s that are contiguous will be replaced with only one ‘X’.

C++:
01 void strReplace(char*& s, char* p)
02 {
03     bool flag=false;
04     int m=0;
05     while(p[m]!=)
06         m++;
07     int fast=0;
08     int slow=0;
09     int p_index=0;
10     while(true){
11         if(s[fast]==){
12             if(flag==true)
13                 s[slow++]=‘X’;
14             for(int i=0;i<p_index;i++)
15                 s[slow++]=p[i];
16             s[slow]=;
17             return;
18         }
19         if(s[fast]==p[p_index])
20             p_index++;
21         else{
22             if(flag==true)
23                 s[slow++]=‘X’;
24             for(int i=0;i<p_index;i++)
25                 s[slow++]=p[i];
26             s[slow++]=s[fast];
27             p_index=0;
28             flag=false;
29         }
30         if(p_index==m){
31             flag=true;
32             p_index=0;
33         }
34         fast++;
35     }
36 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s