How to compact a dynamically allocated string by removing multiple spaces in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void compact_spaces(char *s) {
    char *read = s;
    char *write = s;
    int lastWasSpace = 0;

    while (*read) {
        if (*read == ' ') {
            if (!lastWasSpace) {
                *write++ = ' ';
                lastWasSpace = 1;
            }
        } else {
            *write++ = *read;
            lastWasSpace = 0;
        }
        read++;
    }

    *write = '\0';  // important: terminate new shorter string
}

int main() {
    char *str = malloc(64);
    if (!str) return 1;

    strcpy(str, "This    is   a    test   string");

    printf("Before: '%s'\n", str);

    compact_spaces(str);

    // shrink memory to fit the new string
    size_t newSize = strlen(str) + 1;
    char *tmp = realloc(str, newSize);

    if (tmp) {
        str = tmp;  // only assign if realloc succeeded
    }

    printf("After:  '%s'\n", str);
    printf("New allocated size: %zu bytes\n", newSize);

    free(str);
    
    return 0;
}



/*
run:

Before: 'This    is   a    test   string'
After:  'This is a test string'
New allocated size: 22 bytes

*/

 



answered May 1 by avibootz

Related questions

...