MCPcopy Create free account
hub / github.com/KaisenAmin/c_std / string_replace_all

Function string_replace_all

string/std_string.c:2388–2423  ·  view source on GitHub ↗

* @brief Replaces all occurrences of a substring within a String object with another substring. * * This function searches for all occurrences of the specified oldStr within the given String object * and replaces them with the newStr. If either the String object or the substrings are NULL, * the function logs an error and does nothing. If memory allocation fails during the process, * the fu

Source from the content-addressed store, hash-verified

2386 * @param newStr The substring to replace oldStr with. Must not be NULL.
2387 */
2388void string_replace_all(String *str, const char *oldStr, const char *newStr) {
2389 STRING_LOG("[string_replace_all]: Function start.");
2390
2391 if (str == NULL) {
2392 STRING_LOG("[string_replace_all]: Error - Null String object.");
2393 return;
2394 }
2395 if (oldStr == NULL || newStr == NULL) {
2396 STRING_LOG("[string_replace_all]: Error - Null substring.");
2397 return;
2398 }
2399
2400 String *temp = string_create("");
2401 if (temp == NULL) {
2402 STRING_LOG("[string_replace_all]: Error - Memory allocation failed.");
2403 return;
2404 }
2405
2406 char *start = str->dataStr;
2407 char *end;
2408
2409 while ((end = strstr(start, oldStr)) != NULL) {
2410 *end = '\0';
2411 STRING_LOG("[string_replace_all]: Replacing '%s' with '%s'.", oldStr, newStr);
2412 string_append(temp, start);
2413 string_append(temp, newStr);
2414 start = end + strlen(oldStr);
2415 }
2416
2417 string_append(temp, start);
2418 string_assign(str, temp->dataStr);
2419 string_deallocate(temp);
2420
2421 STRING_LOG("[string_replace_all]: Replacement completed.");
2422 STRING_LOG("[string_replace_all]: Function end.");
2423}
2424
2425
2426/**

Callers

nothing calls this directly

Calls 4

string_createFunction · 0.85
string_appendFunction · 0.85
string_assignFunction · 0.85
string_deallocateFunction · 0.85

Tested by

no test coverage detected