Skip to main content
GameDev.net gamedev.net
🔒 Locked

mystring.replace() syntax example?

Started by gimp Sep 3, 2000 at 11:48 PM 0 replies 750+ views
Original Post
gimp
gimp
I simple want to replace one string with another within a string but I can get the syntax right. string oldstr; string newstr; string data; data.replace(oldstr,newstr); ... or something like that. Any takers??? gimp
Chris Brodie
Grib
Grib
you want either swap(oldstring,newstring) to have oldstring=newstring and newstring=oldstring or data.replace(data.find(oldstring),oldstring.length(),newstring);

find returns the first index of the occurance of the substring pattern in string, length you know, and the third param is the substring to insert.

to replace every occurance of a in s with b

global_replace(string &s,const string &a, const string &b) {
for(size_t pos=s.find(a);pos != string::npos;pos = s.find(a,pos)) {
s.replace(pos,a.length(),b);
}
}

the rough C equivilent of replace would look like

replace(char *s,int start, int end,char *substr) {
char *tail = strdup(s+end+1);
s[start] = '\0';
strcat(s,substr);
strcat(s,tail);
free(tail);
}

replace includes lots of extra magic though.


Edited by - Grib on September 4, 2000 1:49:55 AM

Edited by - Grib on September 4, 2000 1:50:32 AM
Lots of edits

Edited by - Grib on September 4, 2000 1:52:01 AM

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.