// No1 solution: strtok and strcat <br/> char * strreplaceno1 (char * STR, char * oldpart, char * newpart) <br/>{< br/> char temp [256], refer [256]; </P> <p> memset (temp, 0, sizeof (temp )); <br/> strcpy (refer, STR); </P> <p> If (! Memcmp (STR, oldpart, strlen (oldpart) <br/> strcat (temp, newpart); <br/> char * PCH; <br/> PCH = strtok (refer, oldpart); <br/> while (PCH! = NULL) <br/>{< br/> strcat (temp, PCH); <br/> strcat (temp, newpart); <br/> PCH = strtok (null, oldpart); <br/>}< br/> PCH = STR; <br/> If (! Memcmp (STR + strlen (refer)-strlen (oldpart), oldpart, strlen (oldpart) <br/> temp [strlen (temp)-strlen (newpart)] = '/0'; <br/> strcpy (STR, temp); <br/> return STR; <br/>}
// NO2 solution: strstr and strcat <br/> char * strreplaceno2 (char * STR, const char * oldpart, const char * newpart) <br/>{< br/> char temp [256]; <br/> memset (temp, 0,256); <br/> const int size = strlen (oldpart ); <br/> const int sizenew = strlen (newpart); <br/> int off = 0; <br/> char * PCH = strstr (STR, oldpart ); <br/> int pos1 = 0, pos2 = 0; <br/> while (PCH! = NULL) <br/>{< br/> pos2 = PCH-STR; <br/> memmove (temp + off, STR + pos1, pos2-pos1 ); <br/> strcat (temp, newpart); <br/> off ++ = pos2-pos1 + sizenew; <br/> pos1 = pos2 + size; <br/> PCH = strstr (PCH + size, oldpart); <br/>}< br/> PCH = STR; <br/> strcat (temp, STR + pos1); <br/> strcpy (STR, temp); <br/> return STR; <br/>}
Test is not attachedProgramAfter careful testing, there should be no problem.