Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to find and replace all occurrences of a substring in a string with C++

2 Answers

0 votes
#include <iostream>
#include <climits>
  
void string_replace(std::string &s, const std::string &match, 
                           const std::string &replaces, 
                           unsigned int max_replacements = UINT_MAX) {
    int pos = 0;
    unsigned int replacements = 0;
    while ((pos = s.find(match, pos)) != std::string::npos && replacements < max_replacements) {
         s = s.replace(pos, match.length(), replaces);
         pos += replaces.length();
         replacements++;
    }
}
 
int main() {
    std::string s = "c++ c java c++ python c++";
     
    string_replace(s, "c++", "php");
 
    std::cout << s;
}
 
 
 
/*
run:
 
php c java php python php
 
*/

 



answered Jun 25, 2020 by avibootz
edited Jun 25, 2020 by avibootz
0 votes
#include <iostream>

void replace_all_occurrences(std::string &s, std::string math, std::string replaces) {
    size_t pos = s.find(math);
    while(pos != std::string::npos) {
        s.replace(pos, math.size(), replaces);
        pos = s.find(math, pos + replaces.size());
    }
}

int main() {
    std::string s = "c++ c java c++ python c++";
    
    replace_all_occurrences(s, "c++", "php");

    std::cout << s;
}



/*
run:

php c java php python php

*/

 



answered Jun 25, 2020 by avibootz
...