Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int getCnt(const char *const s, const char *const ss) {
- int cnt = 0;
- char *p = strstr(s, ss);
- const int lenSS = strlen(ss);
- while (p) {
- cnt++;
- p = strstr(p + lenSS, ss);
- }
- return cnt;
- }
- char *string_replace_dynamic(const char *where, const char *const what, const char *const replace) {
- char *res = NULL;
- const int cnt = getCnt(where, what);
- if (cnt == 0) {
- return NULL;
- }
- const int lenWhat = strlen(what), lenRep = strlen(replace), whereLen = strlen(where);
- res = malloc(whereLen + cnt * (lenRep - lenWhat) + 1);
- int index = 0;
- while (*where) {
- if (strstr(where, what) == where) {
- strcpy(&res[index], replace);
- index += lenRep;
- where += lenWhat;
- } else {
- res[index] = *where;
- index++;
- where++;
- }
- }
- res[index] = 0;
- return res;
- }//*/
- int main(void) {
- char s1[] = "Acesta este un string si un string este terminat cu 0x00";
- char s2[] = "string";
- char s3[] = "sir";
- char *p = string_replace_dynamic(s1, s2, s3);
- if (p != NULL) {
- puts(p);
- }
- free(p);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement