Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Replace in C++

Tags:

c++

string

macos

I've spent the last hour and a half trying to figure out how to run a simple search and replace on a string object in C++.

I have three string objects.

string original, search_val, replace_val;

I want to run a search command on original for the search_val and replace all occurrences with replace_val.

NB: Answers in pure C++ only. The environment is XCode on the Mac OSX Leopard.

like image 342
Yuval Karmi Avatar asked Sep 21 '09 01:09

Yuval Karmi


People also ask

Can you replace a string in C?

Algorithm to Replace string in CAccept the string, with which to replace the sub-string. If the substring is not present in the main string, terminate the program. If the substring is present in the main string then continue.

Can you use replace on a string?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

What is a string replace?

Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

How do I replace text in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


1 Answers

A loop should work with find and replace

void searchAndReplace(std::string& value, std::string const& search,std::string const& replace)
{
    std::string::size_type  next;

    for(next = value.find(search);        // Try and find the first match
        next != std::string::npos;        // next is npos if nothing was found
        next = value.find(search,next)    // search for the next match starting after
                                          // the last match that was found.
       )
    {
        // Inside the loop. So we found a match.
        value.replace(next,search.length(),replace);   // Do the replacement.
        next += replace.length();                      // Move to just after the replace
                                                       // This is the point were we start
                                                       // the next search from. 
    }
}
like image 146
Martin York Avatar answered Sep 22 '22 09:09

Martin York