Here is your code and its logical error.
int RemoveChars(char *S,char c) {
int i=0;
int spaces=0;
char temp;
for(i=0;S[i]!=0;i++) {
temp=S[i];
if(S[i]!=c) {
// temp = S[i] and S[i] = temp, Hence, S[i] = S[i]
S[i]=temp;
putchar(temp);
}
else
spaces++;
}
return spaces;
}
So basically, the reason why
putchar(temp); works is because you avoid printing character that you want to remove into the screen. However, your string that store in the memory remain the same.
So, I made some correction to your code and it works perfectly, I guess.
int RemoveChars(char *S,char c)
{
int count=0;
int spaces = 0;
char* temp;
// allocate enough memory to store new string after remove.
for(int i=0; S[i] != 0; i++) {
if (S[i]==c)
spaces++;
else
count++;
}
temp = (char*)malloc(count+1);
// write new string without character you want to remove
for(int j=0, i=0; S[i] != '\0'; i++) {
if (S[i]!=c)
temp[j++] = S[i];
}
temp[count] = '\0'; // end string
strcpy(S, temp); // copy new string to old string
free(temp); // de-allocate new string memory.
return spaces;
}