Replacing strings in an array in C -
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char* argv[]) { int = 0; char c; char *array; char *data; char *ret; array = (char *) malloc(100); info = (char *) malloc(strlen(argv[1])+1); strcpy(data, argv[1]); // store word john array called info while((c=getchar())!=eof) // stores words in txt file array { array[i]=c; i++; } ret = strstr(array, data); // find substring (john in case) printf("the substring is: %s\n", ret); *ret = "jack"; // doesn't work here, want replace john jack free(data); free(array); homecoming 0; }
i've done research on strstr tool , seems finds first occurance of substring , returns pointer position. using pointer want modify it, it's not going me.
my terminal @ ubuntu looks when run it:
./a.out john < beatles.txt
my beatles text looks this;
paul
john
ringo
john
in end want array contains 4 names have john replaced jack example. there anyway can using pointer given me strstr tool?
i think need while llop or loop tog et every john in array repalced jack*
you don't want modify pointer, want modify pointer points to. ret
points character, *ret
first character of sequence of characters, in case character 'j'
, can't assign string it. must replace each character of sequence. function memcpy
can help that.
to replace other occurrences of "john" can utilize loop:
while(ret = strstr(array, data)){ printf("the substring is: %s\n", ret); memcpy(ret, "jack", strlen("jack")); }
strstr()
returns null
if not find anything, , when happens going break out of loop.
there problems code too:
you can utilizeargv[1]
in place of data
. it improve re-create file buffer calls fread()
. c
No comments:
Post a Comment