Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ string Map
Hello, everybody, this is my first question, so please notice me if it's something wrong with this.
I want to replace some words without using boost libraries or other .hpp's.
My first attempt was to make a copy of the string, and it was quite inefficient. I'm not very proud of it, so I will post my second attempt where I use addresses.
void ReplaceString(std::string &subject, const std::string &search, const std::string &replace) 
{
    size_t position = 0;
    while ((position = subject.find(search, position)) != std::string::npos)	//if something f***s up --> failure
    {
         subject.replace(position, search.length(), replace);
         position = position + replace.length();
    }
}
 
Because It's not very efficient I want to use another thing, but I got stuck; I want to use a function like
replace_stuff(std::string & a);
with a single parameter using string.replace() and string.find() (parsing it with a for loop or something) and then make use of std::map <std::string,> which is very convenient for me.
 
Can anyone help me with this, please? I started learning C++ few months ago, and I don't know many tips and tricks. I also have some problems with my coherence, so please excuse my poor English.
Best regards,
George.
 
P.S. I want to use it for a large number of input words. (let's say replacing bad words with harmless ones)
Posted 29-Mar-13 10:47am
Edited 29-Mar-13 10:48am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You might create a class, say Replacer:
class Replacer 
{
  std::map<std::string,> replacement;
 
public:
  Replacer()
  {
     // init the map here
     replacement.insert ( std::pair<std::string,std::string>("C#","C++") );
     //...
  }
  void replace_stuff(std::string & a);
}
 
Then the replace_stuff definition would be very similar to your original ReplaceString (it would use map entries instead of the passed parameters).
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Maciej Los 310
1 OriginalGriff 285
2 Afzaal Ahmad Zeeshan 200
3 Sergey Alexandrovich Kryukov 195
4 BillWoodruff 180
0 OriginalGriff 6,499
1 Sergey Alexandrovich Kryukov 6,048
2 DamithSL 5,193
3 Manas Bhardwaj 4,657
4 Maciej Los 4,120


Advertise | Privacy | Mobile
Web02 | 2.8.1411022.1 | Last Updated 29 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100