bigyan

Replace 'a' with "xyz"

May 15th, 2011
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. /*
  2.     Given a char array with words in it, find all 'a' characters and
  3.     replace with some string, say "xyz". Modify the input array, do
  4.     not create a copy of the array.
  5.  
  6.     Date: 110515, Sun 15 May 2011 05:19:16 PM IST
  7.     Link: http://stackoverflow.com/questions/5931945/
  8. */
  9.  
  10. #include <stdio.h>
  11. #include <string.h>
  12.  
  13. int main() {
  14.     char arr[1024];
  15.     char search='a', *replace="xyz";
  16.  
  17.     fgets(arr,1023/strlen(replace),stdin);
  18.     if (arr[strlen(arr)-1]=='\n')
  19.         arr[strlen(arr)-1]='\0';
  20.     puts(arr);
  21.  
  22.     int i, j, k, offset, target;
  23.     for (i=offset=0; i<strlen(arr); ++i)
  24.         if (arr[i]==search)
  25.             offset+=strlen(replace)-1;
  26.  
  27.     target = strlen(arr)+offset;
  28.     for (i=strlen(arr); i>=0; --i) {
  29.         if (arr[i]!=search)
  30.             arr[target--] = arr[i];
  31.         else {
  32.             target -= strlen(replace);
  33.             strncpy(&arr[target+1],replace,strlen(replace));
  34.         }
  35.     }
  36.  
  37.     puts(arr);
  38.  
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment