I need to write a function which will eject excess space from string in C.
Example:
char s[]=" abcde abcde ";
OUTPUT:
"abcde abcde"
Code:
#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
int i, x;
for (i = x = 0; str[i]; ++i)
if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
str[x++] = str[i];
if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
return str;
}
int main() {
char s[] = " abcde abcde ";
printf("\"%s\"", eject(s));
return 0;
}
This code doesn't work for string " "
If this string is found program should print:
""
How to fix this?