Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a char array with words in it, find all 'a' characters and
- replace with some string, say "xyz". Modify the input array, do
- not create a copy of the array.
- Date: 110515, Sun 15 May 2011 05:19:16 PM IST
- Link: http://stackoverflow.com/questions/5931945/
- */
- #include <stdio.h>
- #include <string.h>
- int main() {
- char arr[1024];
- char search='a', *replace="xyz";
- fgets(arr,1023/strlen(replace),stdin);
- if (arr[strlen(arr)-1]=='\n')
- arr[strlen(arr)-1]='\0';
- puts(arr);
- int i, j, k, offset, target;
- for (i=offset=0; i<strlen(arr); ++i)
- if (arr[i]==search)
- offset+=strlen(replace)-1;
- target = strlen(arr)+offset;
- for (i=strlen(arr); i>=0; --i) {
- if (arr[i]!=search)
- arr[target--] = arr[i];
- else {
- target -= strlen(replace);
- strncpy(&arr[target+1],replace,strlen(replace));
- }
- }
- puts(arr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment