Search code examples
cstringc-strings

Eject excess space from string in C


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?


Solution

  • Basically, you need to remove the consecutive space characters between the words in the input string and all leading and trailing space characters of the input string. That means, write code to remove the consecutive space characters in the input string and while removing the consecutive space characters, remove the leading and trailing space characters completely.

    You can do it in just one iteration. No need to write the different functions for removing the leading and trailing spaces of input string, as shown in the other post.

    You can do:

    #include <stdio.h>
    #include <ctype.h>
    
    char * eject (char *str) {
        if (str == NULL) {
            printf ("Invalid input..\n");
            return NULL;
        }
    
        /* Pointer to keep track of position where next character to be write 
         */
        char * p = str;
        for (unsigned int i = 0; str[i] ; ++i) {
            if ((isspace (str[i])) && ((p == str) || (str[i + 1] == '\0') || (str[i] == (str[i + 1])))) {
                continue;
            }
            *p++ = str[i];
        }
    
        /* Add the null terminating character. 
         */
        *p = '\0';
        return str;
    }
    
    int main (void) {
      char s[] = "  abcde    abcde    ";
      printf("\"%s\"\n", eject(s));
    
      char s1[] = "      ";
      printf("\"%s\"\n", eject(s1));
    
      char s2[] = "ab  yz   ";
      printf("\"%s\"\n", eject(s2));
    
      char s3[] = "  ddd xx  jj m";
      printf("\"%s\"\n", eject(s3));
    
      char s4[] = "";
      printf("\"%s\"\n", eject(s4));
    
      return 0;
    }
    

    Output:

    # ./a.out
    "abcde abcde"
    ""
    "ab yz"
    "ddd xx jj m"
    ""