455,902 Members | 1,323 Online
Need help? Post your question and get tips & solutions from a community of 455,902 IT Pros & Developers. It's quick & easy.

# how can I replace a substring in a string

 P: n/a Hi, If I have a string like this: char buff[10]; buff[0] ='h'; buff[1] ='e'; buff[2] ='l'; buff[3] ='l'; buff[4] ='o'; string s(buff); How can i replace 'll' with 'abc' and what if I replace 'll' with 'a', will the 'o' move up by 1 index? Thank you. May 30 '07 #1
7 Replies

 P: n/a si***************@gmail.com skrev: Hi, If I have a string like this: char buff[10]; buff[0] ='h'; buff[1] ='e'; buff[2] ='l'; buff[3] ='l'; buff[4] ='o'; buff[5] = 0; string s(buff); How can i replace 'll' with 'abc' and what if I replace 'll' with 'a', will the 'o' move up by 1 index? replace(s, "ll", "abc"); void replace(std::string &target, std::string &that, std::string &with) { std::string::size_type where = target.find(that); if(where != std::string::npos) { target.replace(target.begin() + where, target.begin() + where + that.size(), with.begin(), with.end()); } } -- OU May 30 '07 #2

 P: n/a On May 30, 10:04 am, "silverburgh.me...@gmail.com" Thank you. May 30 '07 #3

 P: n/a si***************@gmail.com wrote: Hi, If I have a string like this: char buff[10]; buff[0] ='h'; buff[1] ='e'; buff[2] ='l'; buff[3] ='l'; buff[4] ='o'; string s(buff); How can i replace 'll' with 'abc' and what if I replace 'll' with 'a', will the 'o' move up by 1 index? Thank you. Here are all the string class member functions: http://cppreference.com/cppstring/index.html May 30 '07 #4

 P: n/a On Wed, 30 May 2007 19:30:52 +0200, Obnoxious User wrote: [...] >void replace(std::string &target, std::string &that, std::string &with) { const correctness? -- Roland Pibinger "The best software is simple, elegant, and full of drama" - Grady Booch May 30 '07 #5

 P: n/a Roland Pibinger skrev: On Wed, 30 May 2007 19:30:52 +0200, Obnoxious User wrote: [...] >void replace(std::string &target, std::string &that, std::string &with) { const correctness? void replace(std::string & target, std::string const & that, std::string const & with); -- OU May 30 '07 #6

 P: n/a #include int main (void) { std::string S ("hello"); S.replace(S.find("ll"), 2, "abc"); // replace 2 chars at "ll" by "abc" std::cout << S << std::endl; return 0; } and what if I replace 'll' with 'a', will the 'o' move up by 1 index? It decrements by one, from 4 to 3. Thank you. You're welcome. -- Cheers, Robbie Hatley lone wolf aatt well dott com triple-dubya dott Tustin Free Zone dott org May 31 '07 #7

 P: n/a "Obnoxious User"

### This discussion thread is closed

Replies have been disabled for this discussion.