I'm trying to write a function in C, that removes the second array's elements from the first array if the first array fully contains the second array in the exact same order.
I know it's complicated to ask in words, so here are some examples:
If Array-1 is hello and Array-2 is lo, then the output should be hel.
If Array-1 is hello hello and Array-2 is lo, then the output should be hel hel.
If Array-1 is hello and Array-2 is call (the first array does not contain all of the second array), then the output should be hello. (It shouldn't be changed.)
I wrote some code but when I try 2nd example (the hello hello one), it gives me hello hel, not hel hel.
char removeText (char a[], char b[], int lengthA, int lengthB) {
int indexB = 0, i=0;
char d[lengthA];
for (; i<lengthA; i++) {
if (a[i]==b[indexB]) {
indexB++;
if (indexB==lengthB) {
for (int k=0, j=0; k<i-lengthB; j++, k++) {
d[k] = a[j];
}
}
}
else {
i -= indexB;
indexB = 0;
}
}
printf("%s", d);
if(indexB!=lengthB) {
return *a;
}
return *d;
}
int main(void) {
char a[] = "hello hello";
char b[] = "lo";
int c = 11;
int d = 2;
removeText(a, b, c, d);
return 0;
}
The output should be given with return. The printf("%s", d); part is just for trying if the code works or not.
I know what's wrong in my code. The
if (indexB==lengthB) {
for (int k=0, j=0; k<i-lengthB; j++, k++) {
d[k] = a[j];
}
}
part causes the error but how can I fix it?
strstrcould help here...