Reputation: 67
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?
Upvotes: 2
Views: 72
Reputation: 9629
Your problem is in the lines:
for (int k=0, j=0; k<i-lengthB; j++, k++) {
d[k] = a[j];
}
Each time you find a pattern in a
, you copy all a
data into d
, cancelling what have been done before.
To highlight this, you should modify your code with some debug info:
printf("copy to d from a, indexd for %d to %d\n", 0, i-lengthB)
for (int k=0, j=0; k<i-lengthB; j++, k++) {
d[k] = a[j];
}
You could have noticed too that k
and j
are always equal.
One more question, how do you code if the pattern to remove is not at the end of input, or is not present in input ? Try it.
To solve your problem, I would advice a different approach: have a counter for ignored character in a
and copy the character when pattern is not found, something like:
char * removeText (char a[], char b[], int lengthA, int lengthB) {
int indexB = 0, i=0;
int ignored = 0;
char d[lengthA] = "";
for (; i+ignored<lengthA; i++) {
if (a[i+ignored]==b[indexB]) {
indexB++;
if (indexB==lengthB) {
ignored += lengthB;
printf("ignored = %d\n", ignored);
}
}
else {
i -= indexB;
indexB = 0;
printf("d[%d] = a[%d] (%c)\n", i, i+ignored , a[i+ignored ]);
d[i] = a[i+ignored];
}
}
printf("%s", d);
strcpy(a, d);
return a;
}
Upvotes: 1