• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

C++ string replace

SphinCorp

n00b
Joined
Jul 8, 2008
Messages
1
I need to be able to replace all occurences of a string within another. in vb.net it would be:
Code:
string = string.replace("chars to replace", "replace with")

My latest attempt was:
Code:
COM.replace (COM[1], COM[COM.length()], " ", "");

It also failed miserably. How would I do this?

I think it has something to do with this : http://www.cplusplus.com/reference/algorithm/replace.html

But I've never worked with vectors or algorithms before, so I am clueless on how to implement this on a string.

Thanks in advance,
Richard Carson
 
Try

#include <algorithm> // for remove()

remove( string.begin(), string.end(), ' ' );
 
Yes, really. It was more than a decade ago, now.

Regular expressions are useful to know, but they're far more than is needed for simple match-and-replace work.
 
Yes, really. It was more than a decade ago, now.

Regular expressions are useful to know, but they're far more than is needed for simple match-and-replace work.

Okay I remember you now. I think I stumble upon your work blog or something once. Nice to meet you and see you on this forum, Mike.
 
This (based on Monkeyshave's example in the thread I posted) works pretty good:

Code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string replace_all_copy(const string& haystack, const string& needle, const string& replacement) {
    if (needle.empty()) {
        return haystack;
    }
    string result;
    for (string::const_iterator substart = haystack.begin(), subend; ; ) {
        subend = search(substart, haystack.end(), needle.begin(), needle.end());
        copy(substart, subend, back_inserter(result));
        if (subend == haystack.end()) {
            break;
        }
        copy(replacement.begin(), replacement.end(), back_inserter(result));
        substart = subend + needle.size();
    }
    return result;
}

int main() {
    cout << replace_all_copy("zipmeowbam", "meow", "zam") << "\n";
}
 
Back
Top