4 Replies - 2310 Views - Last Post: 30 July 2012 - 03:06 AM

#1 PlasticineGuy   User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Replace all occurences within std::string

Posted 28 February 2010 - 10:41 PM

Description: Add into a source file and call as a function.This snippet takes a std::string and replaces all occurences of one string with a new string.
std::string& replace(std::string& target, const std::string oldstr, const std::string newstr) {
	unsigned int x;
	while(x = target.find(oldstr), x != std::string::npos) {
		target.erase(x, oldstr.length());
		target.insert(x, newstr);
	}
	return target;
}

Is This A Good Question/Topic? 0
  • +

Replies To: Replace all occurences within std::string

#2 PlasticineGuy   User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Re: Replace all occurences within std::string

Posted 28 February 2010 - 10:41 PM

Description: Add into a source file and call as a function.This snippet takes a std::string and replaces all occurences of one string with a new string.
void replace(std::string& target, const std::string oldstr, const std::string newstr) {
	unsigned int x;
	while(x = target.find(oldstr), x != std::string::npos) {
		target.erase(x, oldstr.length());
		target.insert(x, newstr);
	}
}

Was This Post Helpful? 0
  • +
  • -

#3 sarmanu   User is offline

  • D.I.C Lover
  • member icon

Reputation: 967
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Replace all occurences within std::string

Posted 03 March 2010 - 08:45 PM

I wouldn't return a reference, and I'd pass target as copy. In this way, you are not modifying the original string (target).
Was This Post Helpful? 0
  • +
  • -

#4 PlasticineGuy   User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Re: Replace all occurences within std::string

Posted 03 March 2010 - 08:56 PM

I'm just used to functions that edit the target. And I agree; I don't see why I decided to return a reference.
Was This Post Helpful? 0
  • +
  • -

#5 cdk   User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 33
  • Joined: 17-January 07

Re: Replace all occurences within std::string

Posted 12 March 2010 - 01:51 PM

This goes into an infinite loop if newstr contains oldstr: string test = "sand"; replace(test, "and", "panda");
Was This Post Helpful? 0
  • +
  • -

#6 destan   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 30-July 12

Re: Replace all occurences within std::string

Posted 30 July 2012 - 03:06 AM

You can find corrected version of above snippet here: https://gist.github.com/3206181
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1