Reputation: 15
I am trying to remove white spaces from a large array read from a txt file. The strlen() of the array I'll be dealing with is around 15,000~22,500.
Here is my code:
#include <stdio.h>
#include <ctype.h>
void whiteSpace(char str[]){
int i, j;
for (i = 0; str[i] != 0; i ++){
if (isspace(str[i])){
for(j = i; str[j] != 0; j ++){
str[j] = str[j + 1];
}
}
}
}
This works for short arrays, but for larger arrays, I have to use whiteSpace() like twice to get rid of all the white spaces?
I think the algorithm is right, I don't know why it works for short arrays and glitches for larger (15,000~22,500) arrays unless I call the function twice or three times.
Thanks.
Upvotes: 0
Views: 278
Reputation: 1537
This is about the least-efficient way you could accomplish your task, but the specific problem you're seeing is caused by multiple spaces in a row. Imagine that you're scanning along in the i
loop, and you see the first of two spaces. So you start the j
loop, moving everything afterward in the array one character closer to the beginning. The first character you move is the second space, and you put it where the first space is. Eventually, you finish the move, and i
advances to the next character -- which is past the second space that you moved to where the first space was. Now there's a space left in your buffer, but i
is pointing past it, so it'll be left behind.
Upvotes: 1
Reputation: 6629
It doesn't work fine for small arrays. If you have two white spaces in a row, it will error.
The problem is that when it skips one white space, it never checks to see if the shifted character is also a whitespace.
There are several ways to fix it. The easiest, but not the best, is to change your if
to a while
.
Upvotes: 2