Last active
August 29, 2015 13:55
-
-
Save sundeepblue/8762560 to your computer and use it in GitHub Desktop.
In a string replace all occurrence of the given pattern to 'X'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://learn.hackerearth.com/question/168/in-a-string-replace-all-occurrence-of-the-given-pattern-to-x/ | |
/* | |
In a string replace all occurrence of the given pattern to 'X' | |
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'. | |
*/ | |
#include <iostream> | |
#include <cstring> | |
using namespace std; | |
// ================================ C version ================================ | |
bool is_match(char *s, const char *p) { | |
while(*p) { // gist, cannot write (*p && *s) | |
if(*s != *p) return false; | |
s++; | |
p++; | |
} | |
return true; | |
} | |
char* replace_patterns(char *s, const char *patt) { | |
if(!s || *s == '\0' || !patt || *patt == '\0') return NULL; | |
int end = 0, i = 0, plen = strlen(patt); | |
while(s[i] != '\0') { | |
bool match = false; | |
while(is_match(s+i, patt)) { | |
match = true; | |
i += plen; | |
} | |
if(match) s[end++] = 'X'; | |
else s[end++] = s[i++]; | |
} | |
s[end] = '\0'; // necessary | |
return s; | |
} | |
int main() | |
{ | |
char s[] = "abcdeffdfegabcabc"; | |
// char *s = "abcdeffdfegabcabc"; // wrong!!! segment fault!!! | |
cout << replace_patterns(s, "abc"); | |
} | |
// ================================ C++ version ================================ | |
bool is_match(string s, const string& patt) { | |
int ns = s.size(), np = patt.size(); | |
if(ns < np) return false; | |
for(int i=0; i<np; i++) | |
if(s[i] != patt[i]) return false; | |
return true; | |
} | |
string replace_pattern(string& s, const string& p) { | |
if(s.empty()) return ""; | |
if(p.empty()) return s; | |
int ns = s.size(), np = p.size(); | |
if(ns < np) return s; | |
int tail = 0; | |
int i = 0; | |
while(i < ns) { | |
// int j = i, k = 0; // no need to have j and k | |
bool match = false; | |
while(is_match(s.substr(i), p)) { | |
match = true; | |
i += np; | |
} | |
if(match) s[tail++] = 'X'; | |
else s[tail++] = s[i++]; | |
} | |
return s.substr(0, tail); | |
} | |
int main() { | |
string s = "abcabcxaX"; | |
cout << replace_pattern(s, "abc"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment