Advertisement
STANAANDREY

replace str static

Nov 5th, 2024
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4.  
  5. void insert(int pos, char *s, const char *add) {
  6.   int n = strlen(s), lenAdd = strlen(add);
  7.   for (int i = n - 1; i >= pos; i--) {
  8.     s[i + lenAdd] = s[i];
  9.   }
  10.   for (int i = 0; i < lenAdd; i++) {
  11.     s[i + pos] = add[i];
  12.   }
  13. }
  14.  
  15. void del(int pos, int howMuch, char *s) {
  16.   int n = strlen(s);
  17.   for (int i = pos; i < n; i++) {
  18.     s[i] = s[i + howMuch];
  19.   }
  20. }
  21.  
  22. uint32_t string_replace(char *where, const char *what, const char *replace) {
  23.   uint32_t cnt = 0;
  24.  
  25.   char *f = strstr(where, what);
  26.   const int lenRep = strlen(replace);
  27.   const int lenWhat = strlen(what);
  28.   while (f) {
  29.     int pos = f - where;
  30.     insert(pos, where, replace);
  31.     del(pos + lenRep, lenWhat, where);
  32.     cnt++;
  33.     f = strstr(f + lenRep, what);
  34.   }
  35.   return cnt;
  36. }
  37.  
  38. int main(void) {
  39.   char s1[10003] = "", s2[31] = "", s3[31] = "";
  40.   fgets(s1, 900, stdin);
  41.   fgets(s2, 30, stdin);
  42.   fgets(s3, 30, stdin);
  43.   s1[strlen(s1) - 1] = 0;
  44.   s2[strlen(s2) - 1] = 0;
  45.   s3[strlen(s3) - 1] = 0;//*/
  46.   uint32_t cnt = string_replace(s1, s2, s3);
  47.   printf("found: %d\n", cnt);
  48.   puts(s1);
  49.   return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement