Created
January 27, 2021 01:11
-
-
Save arthurbacci/b4b7963ff668977cbb11db60182547e5 to your computer and use it in GitHub Desktop.
Replaces a substring from a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
char *replace_substring_in_string(char *str, char *from, char *to) | |
{ | |
char *result; | |
unsigned int str_len, from_len, to_len; | |
str_len = strlen(str); | |
from_len = strlen(from); | |
to_len = strlen(to); | |
if (str_len + 1 - from_len <= 0) | |
{ | |
return NULL; | |
} | |
int match_at = -1; | |
for (unsigned int i = 0; i < str_len + 1 - from_len; i++) | |
{ | |
char match = 1; | |
for (unsigned int j = 0; j < from_len; j++) | |
{ | |
if (str[i + j] != from[j]) | |
{ | |
match = 0; | |
break; | |
} | |
} | |
if (match == 0) | |
{ | |
continue; | |
} | |
match_at = i; | |
break; | |
} | |
if (match_at == -1) | |
{ | |
return NULL; | |
} | |
result = malloc(str_len + to_len - from_len + 1); | |
memcpy(result, str, match_at); | |
memcpy(&result[match_at], to, to_len); | |
memcpy(&result[match_at + to_len], &str[match_at + from_len], str_len - match_at - from_len); | |
result[str_len + to_len - from_len] = '\0'; | |
return result; | |
} | |
int main() | |
{ | |
char *replace_me = "C is a programming language"; | |
char *replace_from = "is a"; | |
char *replace_to = "is the best"; | |
char *str = replace_substring_in_string(replace_me, replace_from, replace_to); | |
printf("%s\n%s\n", replace_me, str); | |
free(str); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment