Return to Snippet

Revision: 49747
at July 29, 2011 05:51 by kyhle


Initial Code
#include <iostream>
#include <string>

using std::string;
using std::cout;

void RemoveSubStr(const string& r, string& str)
{
	// Make sure that the strings are not empty;
	int rlen = r.length();
	int strlen = str.length();
	
	if (rlen <= 0 || strlen <=0)
		cout << "The string is empty." << '\n';

	int i,j,pos;

	for (i = 0; i < strlen; ++i) {
		pos = i;
		for (j = 0; j < rlen; ++j) {
			if (str[i] != r[j]) {
				break;
			}
			else if ( j == (rlen-1)){
				str.erase(pos,rlen);
				strlen = str.length();// After trimming, the length of string has changed.
				i = -1;
			}
			else
				++i;
		}
	}
}
int main()
{
	string str = "heheo world";
	string r   = "he";

	//RemoveSubStr(r,str);

	// use STL function to remove the substring
	int pos = 0;
	while (pos != -1){
		pos = str.find(r);
		if( pos == -1 ) break;
		else
		str.erase(pos,r.length());
	}

	cout << str << '\n';

	return 0;
}

Initial URL


Initial Description


Initial Title
Remove specified string in a string

Initial Tags


Initial Language
C++