How to find and replace all occurrences of a substring in a string?

c++ replace all occurrences of substring in string
c++ string find and replace
string replace
c++ program to replace a word in a string
find all occurrences of a substring in a string c++
string replace c++
c++ program to find substring in a string and replace
replace all occurrences of a char in a string c++

I need to search a string and edit the formatting of it.

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences of this string.

This is what I have working, sort of:

if(chartDataString.find("*A") == string::npos){ return;}
else{chartDataString.replace(chartDataString.find("*A"), 3,"[A]\n");}

If it doesn't find the string, nothing prints at all, so that's not good.

I know I need to loop through the entire string chartDataString and replace all occurrences. I know there are a lot of similar posts to this but I don't understand (like this Replace substring with another substring C++)

I've also tried to do something like this to loop over the string:

string toSearch = chartDataString;
string toFind = "*A:";
for (int i = 0; i<toSearch.length() - toFind.length(); i++){
   if(toSearch.substr(i, toFind.length()) == toFind){
       chartDataString.replace(chartDataString.find(toFind), 3, "[A]\n");   
   }
}

EDIT taking into consideration suggestions, this in theory should work, but I don't know why it doesn't

size_t startPos=0;
string myString = "*A";
while(string::npos != (startPos = chartDataString.find(myString, startPos))){
    chartDataString.replace(chartDataString.find(myString, startPos), 3, "*A\n");
    startPos = startPos + myString.length();
}   

try the following

const std::string s = "*A";
const std::string t = "*A\n";

std::string::size_type n = 0;
while ( ( n = chartDataString.find( s, n ) ) != std::string::npos )
{
    chartDataString.replace( n, s.size(), t );
    n += t.size();
}

Find and Replace all occurrences of a sub string in C++ – thispointer , how to replace all occurrences of a sub string with new string in C++. For example, we have a string i.e.. “Boost Library is simple C++ Library”. In this article we will discuss how to replace all occurrences of a sub string with new string in C++. For example, we have a string i.e. And we want replace all occurrences of ‘Lib’ with XXX. Let’s see the different methods to do it, If you didn't find what you were looking, then do suggest us in the comments below.

In case boost is available, you can use the following:

std::string origStr = "this string has *A and then another *A";
std::string subStringToRemove = "*A";
std::string subStringToReplace = "[A]";

boost::replace_all(origStr , subStringToRemove , subStringToReplace);

To perform the modification on the original string, OR

std::string result = boost::replace_all_copy(origStr , subStringToRemove , subStringToReplace);

To perform the modifications without modifying the original string.

Replace all occurrences of a substring in a string using JavaScript , Replace all occurrences of a substring in a string using JavaScript. Regular Expression. The general strategy for replacing a substring in the given string is with replace() method. Split() + Join() Another approach is to split the string using given substring as a delimiter, and then join it back together with the Python Main Function Python – Replace all occurrences of a substring in a string Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other. Input : test_str = “geeksforgeeks”

The find function takes an optional second argument: the position from which to begin searching. By default this is zero.

A good position to begin searching for the next match is the position where the previous replacement was inserted, plus that replacement's length. For instance if we insert a string of length 3 at position 7, then the next find should begin at position 10.

If the search string happens to be a substring of the replacement, this approach will avoid an infinite loop. Imagine if you try to replace all occurrences of log with analog, but don't skip over the replacement.

Python String, count – the number of times you want to replace the old substring with the new It returns a copy of the string where all occurrences of a substring is replaced  Sometimes, you want to search and replace a substring with a new one in a column e.g., change a dead link to a new one, rename an obsolete product to the new name, etc. SQL provides a very helpful string function called REPLACE that allows you to replace all occurrences of a substring in a string with a new substring.

It's fairly awkward (and probably not too efficient) to do it in place. I usually use a function along the lines of:

std::string
replaceAll( std::string const& original, std::string const& from, std::string const& to )
{
    std::string results;
    std::string::const_iterator end = original.end();
    std::string::const_iterator current = original.begin();
    std::string::const_iterator next = std::search( current, end, from.begin(), from.end() );
    while ( next != end ) {
        results.append( current, next );
        results.append( to );
        current = next + from.size();
        next = std::search( current, end, from.begin(), from.end() );
    }
    results.append( current, next );
    return results;
}

Basically, you loop as long as you can find an instance of from, appending the intermediate text and to, and advancing to the next instance of from. At the end, you append any text after the last instance of from.

(If you're going to do much programming in C++, it's probably a good idea to get used to using iterators, like the above, rather than the special member functions of std::string. Things like the above can be made to work with any of the C++ container types, and for this reason, are more idiomatic.)

How to replace all occurrences of a string in JavaScript, Find out the proper way to replace all occurrences of a string in plain JavaScript, from regex to other approaches. I'm trying to make a function in C to replace all occurrences of a substring in a string. I made my function, but it only works on the first occurrence of the substring in the bigger string. Here is the code so far:

/// Returns a version of 'str' where every occurrence of
/// 'find' is substituted by 'replace'.
/// - Inspired by James Kanze.
/// - http://stackoverflow.com/questions/20406744/
std::string replace_all(
    const std::string & str ,   // where to work
    const std::string & find ,  // substitute 'find'
    const std::string & replace //      by 'replace'
) {
    using namespace std;
    string result;
    size_t find_len = find.size();
    size_t pos,from=0;
    while ( string::npos != ( pos=str.find(find,from) ) ) {
        result.append( str, from, pos-from );
        result.append( replace );
        from = pos + find_len;
    }
    result.append( str, from , string::npos );
    return result;
/*
    This code might be an improvement to James Kanze's
    because it uses std::string methods instead of
    general algorithms [as 'std::search()'].
*/
}

int main() {
    {
        std::string test    = "*A ... *A ... *A ...";
        std::string changed = "*A\n ... *A\n ... *A\n ...";

        assert( changed == replace_all( test, "*A", "*A\n" ) );
    }
    {
        std::string GB = "My gorila ate the banana";

        std::string gg = replace_all( GB, "gorila", "banana" );
        assert( gg ==  "My banana ate the banana" );
        gg = replace_all( gg, "banana", "gorila"  );
        assert( gg ==  "My gorila ate the gorila" );

        std::string bb = replace_all( GB, "banana", "gorila" );
        assert( gg ==  "My gorila ate the gorila" );
        bb = replace_all( bb, "gorila" , "banana" );
        assert( bb ==  "My banana ate the banana" );
    }
    {
        std::string str, res;

        str.assign( "ababaabcd" );
        res = replace_all( str, "ab", "fg");
        assert( res == "fgfgafgcd" );

        str="aaaaaaaa"; assert( 8==str.size() );
        res = replace_all( str, "aa", "a" );
        assert( res == "aaaa" );
        assert( "" == replace_all( str, "aa", "" ) );

        str = "aaaaaaa"; assert( 7==str.size() );
        res = replace_all( str, "aa", "a" );
        assert( res == "aaaa" );

        str = "..aaaaaa.."; assert( 10==str.size() );
        res = replace_all( str, "aa", "a" );
        assert( res == "..aaa.." );

        str = "baaaac"; assert( 6==str.size() );
        res = replace_all( str, "aa", "" );
        assert( res == "bc" );
    }
}

How to Replace All Occurrences of a String in JavaScript, You can use the JavaScript replace() method in combination with the regular expression to find and replace all occurrences of a word or substring inside any  You can use the JavaScript replace() method in combination with the regular expression to find and replace all occurrences of a word or substring inside any string. Let's check out an example to understand how this method basically works:

String replaceAll() example - How to replace all , You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. to replace instances of an expression in a string with a fixed string, then you can use a simple required to String.replaceAll(); if the replacement string isn't fixed, then you can use a loop with a Pattern in addition to Matcher in which you reach complete control over the replacement string.

How to Replace all occurrences of a substring in a String in Java?, In this tuotrial, we will learn how to use String.replaceAll(String otherString) to replace all occurrences of a sub-string with another new string in a string using  Find out the proper way to replace all occurrences of a string in plain JavaScript, from regex to other approaches How to replace all occurrences of a string in JavaScript Published Jul 02, 2018 , Last Updated Sep 29, 2019

How to replace all occurrences of a substring from a string with a , collapse every occurence of your padding charactere '\0' to get a string without "​holes". In C++ the first function would look like: void find_replace(; const  Question: Tag: javascript I am trying to do string.replace() on the * character. The string has multiple occurrences of the character and so I need to do a global replace, but if I do what seems natural it produces the comment tag.

Comments
  • What about using std::regex or boost::regex?
  • Boost has a replace_all function.
  • But if string is 1MB and replaced char is found inside for 100 times, then this means mallocing 100MB just for 100bytes.
  • How do I find out what the position of the first occurrence is?
  • @Sarah You are already using it in your example code to perform the first replacement! It is the return value of find.
  • The algorithm is something like 1. Initialize a position to zero; 2. Find the substring starting at the position. 3. If the substring is not found, you are done. Otherwise: 4. replace the substring at the position. 5. Add the length of the replacement string to the position. 6. Go back to step 2.
  • I would genuinely like to use this but I don't think it works and I am not exactly sure how to make it work. When I call replaceAll(chartDataString, "*A", "[A]\n"); nothing actually happens and I don't know enough to know how to make it work
  • @Sarah It works for me. (It is, in fact, adopted from production code.) Are you sure that chartDataString contains the sequence "*A"? And are you looking at the return value; this function doesn't change anything in original, from or to? (Generally speaking, it's a lot cleaner to use pure functions, rather than to have functions which modify existing objects. Performance sometimes dictates otherwise, but as a general rule, prefer pure functions to mutating functions.)