Replace Multiple Spaces with Single Space in C

In text processing, sometimes strings contain multiple adjacent spaces which we want to reduce to a single space. This can be achieved using a simple function in C.

We will write a function that processes a string and replaces consecutive spaces with a single space while preserving the words.

Logic to Replace Multiple Spaces

1. Initialize a read index (i) and a write index (j).

2. Traverse the string character by character.

3. Copy the current character to the write index if it is not a space or if the previous character was not a space.

4. Increment the write index for each copied character.

5. Null terminate the string at the end.

This ensures that multiple consecutive spaces are reduced to a single space.

C Program to Replace Multiple Spaces with Single Space

C
Function to remove adjacent multiple spaces
#include <stdio.h>
#include <string.h>

void replaceSpaces(char str[]) {
    int i = 0, j = 0;
    int n = strlen(str);
    int spaceFlag = 0; // To track consecutive spaces

    while(str[i] != '\0') {
        if(str[i] != ' ') {
            str[j++] = str[i];
            spaceFlag = 0;
        } else {
            if(spaceFlag == 0) {
                str[j++] = ' '; // keep only one space
                spaceFlag = 1;
            }
            // else skip multiple spaces
        }
        i++;
    }
    str[j] = '\0'; // terminate string
}

int main() {
    char str[] = "Hello    world!  How    are   you?";

    printf("Original String: \"%s\"\n", str);
    replaceSpaces(str);
    printf("Modified String: \"%s\"\n", str);

    return 0;
}
Output:
Original String: "Hello    world!  How    are   you?"
Modified String: "Hello world! How are you?"

Explanation

• 'replaceSpaces' function uses two pointers: one for reading the string and one for writing characters back to the string.

• 'spaceFlag' ensures that only the first space in a sequence is copied, and subsequent spaces are ignored.

• At the end, the string is null-terminated to properly end the modified string.

• This approach modifies the original string in place without using extra memory.

Advantages of This Approach

• In-place modification saves memory.

• Handles any number of consecutive spaces.

• Preserves original words and order.

Conclusion

Replacing multiple adjacent spaces with a single space is useful for cleaning up input text, formatting strings, and preparing data for further processing. The C function presented here is simple, efficient, and works for any string containing multiple spaces.