C code to remove spaces from a string

Write a C function to remove spaces from a string. The function header should be
void removeSpaces(char *str)

ie, “abc de” -> “abcde”

Here might be a common interview question testing your C skills:

It can be implemented in just 5 lines of code, shown below:

Of course, this is for illustration purpose and to show how elegant C code can be.

I probably wouldn’t program like this in the industry just for clarity sake. There are no parenthesis indicating clear scope and it’s not obvious what *p1++ means to some programmers (*p1++ is the same as *(p1++) due to ++ having higher precedence).

VN:F [1.9.22_1171]
Rating: 3.7/5 (24 votes cast)
C code to remove spaces from a string, 3.7 out of 5 based on 24 ratings

35 thoughts on “C code to remove spaces from a string

  1. 1337c0d3r

    Isn't that's what your teacher says to make sure you always null-terminate your string?

    I just found another gotcha in the code — It did not check for NULL pointer. If NULL is passed into the function, the world might explode this time.

    VA:F [1.9.22_1171]
    +3
  2. Anonymous

    void removeSpaces(char *array)
    {
    char *endPtr = array;
    while(*endPtr)
    {
    if(*endPtr == ' ')
    {
    endPtr++;
    }
    else
    {
    *array++ = *endPtr++;
    }
    }
    *array = '\0';
    }

    VA:F [1.9.22_1171]
    +4
    1. Anonymous

      void remSpc(char *str){
      char *p1 = str;
      while (*p1){
      if (*p1 == ‘ ‘){
      p1++;
      }
      else{
      *str++ == *p1++;
      }
      }
      *str = ”;
      }

      char str1 [] = ” Dumb you are.. dumbo “;
      remSpc(str1);
      printf(“%s\n”, str1);

      Dumb you are.. d

      VA:F [1.9.22_1171]
      0
  3. Venki

    The code is fine, not at the production level. Usually it is the responsibility of upper level code to take care of function limitations. For example NULL checking need not be performed in the function, eventhough no harm.

    In C every string should be NUL terminated. NUL is the only delimiter. If the string is not NULL terminated, it fails even at other functions that depends on NUL character of C strings.

    In C++ one can enforce the size of string using Class encapsulation mechanism.

    One correction, * and ++ fall in the same group of priority. ++ and * are having right to left associativity. Hence *p++ is interpreted as *(p++), i.e. increment the pointer in reserved place and dereference before updating pointer.

    Good work, keep it up. I would also suggest to post possible test cases (no need of code) thinking in destructive way of the code snippet, both from algorithm perspective and from language perspective.

    VA:F [1.9.22_1171]
    +1
  4. moonus

    My idea is that, the code is good for discussion of the *p++, but not very efficient enough. There is no need to overwrite the same place with its own value. So I would agree with the Anonymous at 4th floor more.

    By the way, if NULL is passed in, no while condition can be true, the world is saved, right? Did I miss something?

    VA:F [1.9.22_1171]
    0
    1. 1337c0d3r Post author

      You must declare str as array notation, ie:
      char str[]=” abc de sdfws ssd sfdf sdfsd sds “;

      Declaring str as char * means that str cannot be modified. You will most likely get a seg fault if you try that.

      VN:F [1.9.22_1171]
      +1
      1. Nishant Mishra

        Well, I think str[] is a sort of constant pointer, while *str is modifiable…
        What I mean is, suppose :

        char str[]=”My name”;
        char *str2=”your name”;

        //Now

        str++; // illegal
        str2++; // legal.

        You can do this:
        *(str+3)=’M’;

        But you can’t do this:
        str+3=str;

        And also you can edit str2 as:
        str2=str2+5;

        basically str is a unmodifiable lvalue, while str2 is modifiable lvalue…

        Please, explain me where I am wrong, if I am..

        VN:F [1.9.22_1171]
        -1
  5. UnderMonkey

    @1337c0d3r, love all your post! Though in this problem, you should probably insert a ” to mark the new end of the char array.

    void removespace(char *s){
    char *p = s;
    if(!*s) return;
    while((*s++)){
    if(*s == ‘ ‘) continue;
    *p++ = *s;
    }
    *p = ”;
    }

    VN:F [1.9.22_1171]
    -1
  6. Akshay Khokhar

    int i=0,j=0;

    while( str[i] != ”)
    {
    if(str[i]!=’ ‘)
    {
    str[j]=str[i];
    j++;
    }
    i++;

    }

    VA:F [1.9.22_1171]
    +1
  7. vamsi

    In Java

    VN:F [1.9.22_1171]
    +4
  8. kavish dwivedi

    I have a very out of the way solution:

    VN:F [1.9.22_1171]
    +1
    1. Riccardo

      Ris O(N^2) because strlen is O(N).
      Do it in a real interview and you forget the job.

      Suppose the string is one megebyte. Your solution would perform one tera ops instead of one million. Is worst than crashing would take the CPU for days.

      VA:F [1.9.22_1171]
      -1
    2. Riccardo

      Ris O(N^2) because strlen is O(N).

      Suppose the string is one megebyte. Your solution would perform one tera ops instead of one million. Is worst than crashing would take the CPU for days.

      VA:F [1.9.22_1171]
      0
  9. brainless

    If there is no space in the string, what’s the point to copy *p2 to *p1 so many times?

    VN:F [1.9.22_1171]
    +3
  10. benh

    Minor tweaks from the author’s solution
    void removeSpace(char * input)
    {
    char * p1, *p2;
    p1 = p2 = input;
    if(input == NULL || !*input )
    return;

    do {
    while(*p2==’ ‘)
    p2++;
    } while (*p1++=*p2++);
    }

    int main()
    {
    //cout << "Hello world!" << endl;

    char a[30];
    strcpy(a, " ab dsf asd ");
    removeSpace(a);
    cout << a << "___"<<endl;
    strcpy(a, "");
    removeSpace(a);
    cout << a << "___";
    return 0;
    }

    VN:F [1.9.22_1171]
    0
  11. Pingback: Remove White Spaces From A String | Coding Inspiration

  12. Abhinav Gupta

    #include
    #include

    using namespace std;

    void removeBlankSpaces(char str[]) {
    int j;
    int len = strlen(str);
    for(int i=0; i<len; i++) {
    if(str[i] != ' ') {
    str[j] = str[i];
    j++;
    }
    }
    str[j] = '';
    }

    int main()
    {
    char str[] = " abc de hg ai ";
    removeBlankSpaces(str);
    cout << str << endl;
    return 0;
    }

    VN:F [1.9.22_1171]
    0
  13. itachi

    Here is my solution
    Time Complexity: O(n)
    Space Complexity: O(1)

    int main() {
    char str[100];
    char i=0,j=0;
    gets(str);
    while(str[i])
    {
    if(str[i] == ' ')
    {
    i++;
    continue;
    }
    str[j++]=str[i];
    i++;
    }
    str[j] = '';
    cout<<str;
    return 0;
    }
    </code<

    VN:F [1.9.22_1171]
    +1
  14. NaniAjay

    #include
    #include
    int main()
    {
    int i=0;
    char a[]=”Hi baby can u plzzz give me one kiss….”;
    for(i=0;i<strlen(a[i]);i++)
    {
    if(a[i]==' ')
    a[i]='$';

    printf("%c",a[i]);
    }
    getch();
    return 0;
    }

    VA:F [1.9.22_1171]
    0
  15. skysbjdy

    int count(char *str) {
    int res = 0;
    char* p1 = str;
    while (*p1++ != ‘\0’) {
    if(*p1 != ‘ ‘) res++;
    while(*p1 != ‘ ‘ && *p1 != ‘\0’) p1++; //pass the current word
    }
    return res;
    }

    VA:F [1.9.22_1171]
    0

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use the <code> tag to embed your code.

*