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

good method for a replace function for chars?

Started by amemorex Dec 21, 2001 at 1:41 PM 0 replies 300+ views
Original Post
amemorex
amemorex
* im working with chars, no..do not mention STL..that is out of the question, because i am trying to get more experienced with chars, basically this is a learning experience. * anyway, i''m trying to make a replace function for a string..i can easily do one that replaces one character, like...
  
void s_replace(char *string, char find, char replace) {
  //blah blah blah

       if (string[i] == find) {
          string[i] = replace;
       }
}
  
that pretty much works, but i want to be able to replace a STRING of letters, like void s_replace(char *string, char *find, char *replace) { } so that i can replace "bob" with "robert" if i wanted to.. but i im not sure how to approach this..help?
CheeseGrater
CheeseGrater
This seems pretty homeworkish, so I''n not going to post code. But...

You need to allocate a new string in your function and return that, since the length of the string may change. Probably pass the string variable as a pointer to a pointer instead so you can reallocate the memory. Then you just loop up the string, copying characters if your find string doesn''t match, and copying in your replace if it does.

Topic Locked

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

Sign in to reply to this topic.