The problem is that you are not decreasing the value of i after deleting the character.
Explain it better. If you find a character that is not one of the characters you want, and you delete it, then all other characters will move one index back. And then, you increase i , because of which you will not check the correctness of the first character that you returned in this iteration, thereby, this character is skipped.
Let's look at your string . After entering, it becomes
1 2 3 1 2 3 ^ ^ ^ ^ ^ ^ ^ ^ ^ 0 1 2 3 4 5 6 7 8
Now let's skip a few iterations and move on to the part where the space with index 3 is deleted. After deleting it, your line will look like
1 2 3 1 2 3 3 ^ ^ ^ ^ ^ ^ ^ ^ ^ 0 1 2 3 4 5 6 7 8
But then you go to the next index i , that is, to i = 4 , and the space in i = 3 remains as it is. And after this iteration, it becomes
1 2 3 1 2 3 3 3 ^ ^ ^ ^ ^ ^ ^ ^ ^ 0 1 2 3 4 5 6 7 8
As you can see, the space remains there. This is what causes the problem.
So, you need to reduce i and length so that all characters are marked.
You have to do
void eliminateJunk(char string[MAX]) { int i,j; char stringOut[MAX]; int length = strlen(string) - 1; for(i=0; i <= length; i++) { if( string[i] != '+' && string[i] != '-' && string[i] != '*' && string[i] != '/' && !( isdigit(string[i]) ) ) { for(j=i; j < length; j++) { string[j] = string[j+1]; } i--; length--; } } string[i]='\0'; printf("%s",string); }
I also added
string[i]='\0';
So you can finish the array with the desired length.