Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. // Задача 7. Дефинирайте стринг „I am a poor programmer”. Заменете през пойнтер “poor” с “great”.
  6.  
  7. char *replaceWord(const char *s, const char *pcOldWord, const char *pcNewWord)
  8. {
  9.     char *pcResult;
  10.     int i, iCounter = 0;
  11.     int iNewWordLength = strlen(pcNewWord);
  12.     int iOldWordLength = strlen(pcOldWord);
  13.  
  14.     for (i = 0; s[i] != '\0'; i++)
  15.     {
  16.         if (strstr(&s[i], pcOldWord) == &s[i])
  17.         {
  18.             iCounter++;
  19.             i += iOldWordLength - 1;
  20.         }
  21.     }
  22.  
  23.     pcResult = (char *)malloc(i + iCounter * (iNewWordLength - iOldWordLength) + 1);
  24.  
  25.     i = 0;
  26.     while (*s)
  27.     {
  28.         if (strstr(s, pcOldWord) == s)
  29.         {
  30.             strcpy(&pcResult[i], pcNewWord);
  31.             i += iNewWordLength;
  32.             s += iOldWordLength;
  33.         }
  34.         else
  35.             pcResult[i++] = *s++;
  36.     }
  37.  
  38.     pcResult[i] = '\0';
  39.     return pcResult;
  40. }
  41.  
  42. int main()
  43. {
  44.     char str[] = "I am a poor programmer";
  45.     char c[] = "poor";
  46.     char d[] = "good";
  47.     char *result = NULL;
  48.  
  49.     printf("Old string: %s\n", str);
  50.     result = replaceWord(str, c, d);
  51.     printf("New String: %s\n", result);
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement