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'.   

Solution: 

string& repalce(string& s, string ch)     // the only problems we need to care about here are string resize after
{                                         // been replaced each time
	int size_s = s.size() - 1;
	if(!size_s)
		return s;
	
	else
	{
		int i_s = 0;
		int i_t = 0;
		int i_temp = 0;
		while(i_temp <= size_s)
		{
			if(s[i_s]=='a')
			{
				i_t = i_s;
				int n = 0;
				while(s[i_s]=='a'&& (size_s-i_temp)>=2)
				{
						string sub_s = s.substr(i_s,3);
						if(sub_s == "abc") 
						{
							i_s = i_s + 3;
							i_temp = i_temp + 3;
							n++;	
						}
						else break;
				}
				if(n!=0)
				{
					s.replace(i_t, 3*n, ch);
					i_s = i_s - 3*n + 1;
				}
				else
				{
					i_s = i_s + 1;
					i_temp = i_temp + 1;
				
				}
			}
			else
			{
				i_s = i_s + 1;
				i_temp = i_temp + 1;
			}
		
		}
		return s;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	string result;
	string ch = "X";
	string s = "abcwzxabcabccbaabcccda";
	result = repalce(s,ch);
	cout << result;
	return 0;
}

  

posted @ 2013-07-25 01:34  pgu2  阅读(199)  评论(0)    收藏  举报