C Program to Remove Spaces from a String

C Program to Remove Spaces from a String

Removing spaces from a string is a common operation in text processing, especially when cleaning input data or preparing text for further analysis. In C, strings are arrays of characters ending with a null terminator (\0). By traversing the string and copying only non-space characters, we can efficiently remove all spaces. In this tutorial, we will learn how to remove spaces from a string using loops, pointers, and functions.

Understanding the Problem

Given a string, the goal is to produce a new string (or modify the original) without any spaces. For example, if the input string is "C programming is fun", the resulting string should be "Cprogrammingisfun".

The basic approach is:

  1. Traverse the string character by character.
  2. If the character is not a space, copy it to the next position in the output string.
  3. Skip spaces.
  4. Terminate the resulting string properly with \0.

This problem demonstrates string traversal, conditional checks, and in-place modification in C.

Program 1: Using a Loop

The simplest method uses a loop to traverse the string and copy non-space characters.

#include <stdio.h>

int main() {

    char str[200];
    int i, j = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline character
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] == '\n') str[i] = '\0';
    }

    // Remove spaces
    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] != ' ') {
            str[j++] = str[i];
        }

    }

    str[j] = '\0';

    printf("String without spaces: %s\n", str);

    return 0;

}

In this method, j tracks the position in the new string. Each non-space character is copied forward, effectively removing spaces.

Program 2: Using Pointers

Pointers can traverse the string without using array indices, making the code more memory-friendly.

#include <stdio.h>

int main() {

    char str[200], *src, *dest;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline
    for (src = str; *src != '\0'; src++) {

        if (*src == '\n') {
            *src = '\0';
            break;
        }

    }

    src = dest = str;

    while (*src != '\0') {

        if (*src != ' ') {
            *dest = *src;
            dest++;
        }

        src++;

    }

    *dest = '\0';

    printf("String without spaces: %s\n", str);

    return 0;

}

This pointer-based method highlights how strings are sequences of memory locations and how in-place modification works efficiently.

Program 3: Using a Function

For better code organization, we can create a function that removes spaces from any given string.

#include <stdio.h>

void removeSpaces(char *str) {

    char *src = str, *dest = str;

    while (*src != '\0') {

        if (*src != ' ') {
            *dest = *src;
            dest++;
        }

        src++;

    }

    *dest = '\0';

}

int main() {

    char str[200];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == '\n') str[i] = '\0';
    }

    removeSpaces(str);

    printf("String without spaces: %s\n", str);

    return 0;

}

Using a function improves readability, reusability, and makes the code easier to maintain in larger programs.

Program 4: Using isspace()

The isspace() function checks if a character is a whitespace character (like space, tab, newline).
This makes the program more robust than just checking ' '.

#include <stdio.h>
#include <ctype.h>

int main() {

    char str[200];
    int i, j = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline character
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] == '\n') str[i] = '\0';
    }

    // Remove all whitespace using isspace()
    for (i = 0; str[i] != '\0'; i++) {

        if (!isspace((unsigned char)str[i])) {
            str[j++] = str[i];
        }

    }

    str[j] = '\0';

    printf("String without spaces: %s\n", str);

    return 0;

}

Here, isspace() takes care of spaces, tabs, and even newlines, making it more general.

Program 5: Using Recursion

Recursion can be used by processing one character at a time and shifting when spaces are found.

#include <stdio.h>

// Recursive function to remove spaces
void removeSpacesRec(char *str) {

    if (*str == '\0') return;  // base case: end of string

    if (*str == ' ') {

        // Shift left if current char is a space
        for (char *p = str; *p != '\0'; p++) {
            *p = *(p + 1);
        }

        removeSpacesRec(str); // recheck at same position

    } else {
        removeSpacesRec(str + 1); // move to next character
    }

}

int main() {

    char str[200];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == '\n') str[i] = '\0';
    }

    removeSpacesRec(str);

    printf("String without spaces: %s\n", str);

    return 0;

}

This recursive version works by shifting characters left when a space is found, then continuing until the string ends.

Program 6: Using strtok()

The strtok() function breaks a string into tokens separated by spaces.
By joining the tokens back together, we effectively remove all spaces.

#include <stdio.h>
#include <string.h>

int main() {

    char str[200];
    char *token;
    char result[200] = "";

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline character
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == '\n') str[i] = '\0';
    }

    // Split the string into words
    token = strtok(str, " ");

    while (token != NULL) {

        strcat(result, token);   // append word without adding spaces
        token = strtok(NULL, " ");

    }

    printf("String without spaces: %s\n", result);

    return 0;

}

This method is useful when you want to process strings word by word, since strtok() can handle multiple spaces neatly.

Program 7: Using memmove()

The memmove() function safely moves memory blocks, even when they overlap.
We can use it to “shift” characters left each time a space is found.

#include <stdio.h>
#include <string.h>

int main() {

    char str[200];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline character
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == '\n') str[i] = '\0';
    }

    // Traverse and remove spaces using memmove
    for (int i = 0; str[i] != '\0'; i++) {

        if (str[i] == ' ') {

            memmove(&str[i], &str[i + 1], strlen(str) - i);
            i--; // recheck current index after shift

        }

    }

    printf("String without spaces: %s\n", str);

    return 0;

}

Here, when a space is found:

  • memmove() shifts everything after it one position to the left.
  • i-- ensures the program checks the new character that moved into this spot.

Summary: 7 Ways to Remove Spaces in C

Different problems need different tools. Here are seven approaches, from the simplest loops to library-powered methods. Each shines in its own way, depending on readability, efficiency, and flexibility.

MethodHow It WorksProsCons
1. LoopUses array indices, copies non-space chars forward.Easy to understand, beginner-friendly.Only checks ' ' (ignores tabs, etc).
2. PointersUses src and dest pointers to traverse and overwrite.Efficient, no extra array needed.Harder to read for beginners.
3. FunctionWraps removal logic into a separate function.Reusable, clean, modular.Same as pointers, but adds function call overhead.
4. isspace()Uses <ctype.h> isspace() to check whitespace.Handles spaces, tabs, newlines.Needs typecast to unsigned char for safety.
5. RecursionProcesses one char at a time, shifts if space.Elegant, shows recursive thinking.Less efficient (stack + repeated shifting).
6. strtok()Splits into tokens (words) and rejoins.Great for word-based processing, handles multiple spaces.Requires extra buffer, destroys original string.
7. memmove()Shifts characters left when a space is found.Direct, uses built-in function.Can be slower if many spaces (repeated shifts).

FAQs

1. Can this program remove tabs and other whitespace?
Yes. If you use isspace() from <ctype.h>, it will handle spaces, tabs, newlines, and other whitespace characters, not just ' '.

2. Does this work with empty strings?
Yes. All methods will safely return an empty string if no characters are entered.

3. Can I remove spaces only from the beginning or end of a string?
Yes. You can adapt the logic to trim only leading or trailing spaces while keeping spaces inside the string untouched.

4. Is it efficient for large strings?
Most methods are efficient because they work in-place and traverse the string once. However, recursive and memmove() approaches may be slower if there are many spaces, since they repeatedly shift characters.

5. Which method should I use?

  • Use loop/pointers for simplicity and speed.
  • Use isspace() for all whitespace.
  • Use function for reusability.
  • Use recursion for learning.
  • Use strtok() if you care about words.
  • Use memmove() if you want to practice library functions.

Conclusion

Removing spaces is a simple but essential step in text processing.
We explored seven different methods: from basic loops and pointer tricks to recursion, isspace(), strtok(), and even memmove().

Each method has its strengths. Some are best for clarity and learning, while others are better for efficiency and flexibility. By understanding all of them, you gain a strong foundation for more advanced string handling tasks like trimming, tokenizing, formatting, and parsing input in real-world C programs.

References & Additional Resources

A curated list of tutorials, documentation, and textbooks for learning how to manipulate strings and pointers in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – Authoritative text covering strings, arrays, and fundamental C programming concepts.
  2. Tutorialspoint: C Strings – Introduction to string handling functions and operations in C.
  3. Cprogramming.com: Pointers in C – Clear explanation of pointers and how they are applied in string manipulation.
  4. cplusplus.com: ctype.h Functions – Reference for standard C character-handling functions like isspace() and isalpha().
Scroll to Top