Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. char *fnReplace(char sString[], char sPoor[], char sGreat[]); // Function to replace the words
  5.  
  6. int main()
  7. {
  8.     char sString[] = "I am a poor programmer";
  9.     printf("Input string: %s\n", sString);
  10.     printf("Replaced substring: %s\n", fnReplace(sString, "poor", "great"));
  11.     return 0;
  12. }
  13.  
  14. char *fnReplace(char sString[], char sPoor[], char sGreat[])
  15. {
  16.     int iStLen  = strlen(sString); // In this variable we save the length of sString[] (without the '\0')
  17.     int iPoorLen = strlen(sPoor);  // In this variable we save the length of sPoor[] (without the '\0')
  18.     int iGreatLen = strlen(sGreat); // In this variable we save the length of sGreat[] (without the '\0')
  19.     char *pPointer = NULL; // We use this pointer for the loop.
  20.     for (pPointer = sString; pPointer = strstr(pPointer, sPoor); ++pPointer)
  21.     {
  22.       if (sPoor != sGreat) // Here we check if the words are with different length (in this case they are) and make the array "bigger", so we can save and see whole of it.
  23.       {
  24.         memmove(pPointer + iGreatLen, pPointer + iPoorLen, iStLen - (pPointer - sString) + iGreatLen);
  25.         memcpy(pPointer, sGreat, iGreatLen);
  26.       }
  27.     }
  28.     return sString;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement