Click here to Skip to main content
15,896,532 members

Replace whole words from a sequence of words in a string

George Netu asked:

Open original thread
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.
C++
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
C++
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)
Tags: C++, String, Mapping

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900