home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / snip1292.zip / STRREPL.C < prev    next >
C/C++ Source or Header  |  1992-07-03  |  2KB  |  74 lines

  1. /*
  2.    --------------------------------------------------------------------
  3.    Module:     REPLACE.C
  4.    Author:     Gilles Kohl
  5.    Started:    09.06.1992   12:16:47
  6.    Modified:   09.06.1992   12:41:41
  7.    Subject:    Replace one string by another in a given buffer.
  8.                This code is public domain. Use freely.
  9.    --------------------------------------------------------------------
  10. */
  11.  
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15.  
  16. /*
  17.  * StrReplace: Replace OldStr by NewStr in string Str.
  18.  *
  19.  * Str should have enough allocated space for the replacement, no check
  20.  * is made for this. Str and OldStr/NewStr should not overlap.
  21.  * The empty string ("") is found at the beginning of every string.
  22.  *
  23.  * Returns: pointer to first location behind where NewStr was inserted
  24.  * or NULL if OldStr was not found.
  25.  * This is useful for multiple replacements, see example in main() below
  26.  * (be careful not to replace the empty string this way !)
  27.  */
  28.  
  29. char *StrReplace(char *Str, char *OldStr, char *NewStr)
  30. {
  31.       int OldLen, NewLen;
  32.       char *p, *q;
  33.  
  34.       if(!(p = strstr(Str, OldStr)))
  35.             return p;
  36.       OldLen = strlen(OldStr);
  37.       NewLen = strlen(NewStr);
  38.       memmove(q = p+NewLen, p+OldLen, strlen(p+OldLen)+1);
  39.       memcpy(p, NewStr, NewLen);
  40.       return q;
  41. }
  42.  
  43. #ifdef TEST
  44.  
  45. /*
  46.  * Test main().
  47.  * Given two arguments, replaces the first arg. in the lines read from
  48.  * stdin by the second one.
  49.  * Example invocation:
  50.  * replace printf puts <replace.c
  51.  * will replace all printf's by puts in replace's source.
  52.  *
  53.  */
  54.  
  55. int main(int argc, char *argv[])
  56. {
  57.       char buf[200];
  58.       char *Start;
  59.  
  60.       if(argc != 3)
  61.             exit(1);
  62.  
  63.       /* Repeat until all occurences replaced */
  64.  
  65.       while(Start = gets(buf))
  66.       {
  67.             while(Start = StrReplace(Start, argv[1], argv[2])) ;
  68.             printf("%s\n", buf);
  69.       }
  70.       return 0;
  71. }
  72.  
  73. #endif TEST
  74.