Advertisement
STANAANDREY

replace str dynamic

Nov 5th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int getCnt(const char *const s, const char *const ss) {
  6.   int cnt = 0;
  7.   char *p = strstr(s, ss);
  8.   const int lenSS = strlen(ss);
  9.   while (p) {
  10.     cnt++;
  11.     p = strstr(p + lenSS, ss);
  12.   }
  13.   return cnt;
  14. }
  15.  
  16. char *string_replace_dynamic(const char *where, const char *const what, const char *const replace) {
  17.   char *res = NULL;
  18.   const int cnt = getCnt(where, what);
  19.   if (cnt == 0) {
  20.     return NULL;
  21.   }
  22.   const int lenWhat = strlen(what), lenRep = strlen(replace), whereLen = strlen(where);
  23.   res = malloc(whereLen + cnt * (lenRep - lenWhat) + 1);
  24.   int index = 0;
  25.   while (*where) {
  26.     if (strstr(where, what) == where) {
  27.       strcpy(&res[index], replace);
  28.       index += lenRep;
  29.       where += lenWhat;
  30.     } else {
  31.       res[index] = *where;
  32.       index++;
  33.       where++;
  34.     }
  35.   }
  36.   res[index] = 0;
  37.   return res;
  38. }//*/
  39.  
  40. int main(void) {
  41.   char s1[] = "Acesta este un string si un string este terminat cu 0x00";
  42.   char s2[] = "string";
  43.   char s3[] = "sir";
  44.   char *p = string_replace_dynamic(s1, s2, s3);
  45.   if (p != NULL) {
  46.     puts(p);
  47.   }
  48.   free(p);
  49.   return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement