Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to remove extra whitespace from a string in C

1 Answer

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

/* ------------------------------------------------------------
   normalize_whitespace
   ------------------------------------------------------------
   Removes extra whitespace from a string:

   - Trim leading whitespace
   - Trim trailing whitespace
   - Collapse multiple internal whitespace into a single space

   The algorithm performs a single linear scan and writes into
   an output buffer provided by the caller.
   ------------------------------------------------------------ */
void normalize_whitespace(const char *input, char *output) {

    int in_ws = 0;      /* Tracks whether we are inside a whitespace run */
    int started = 0;    /* Tracks whether we've copied the first non-space */
    size_t j = 0;       /* Write index for output */

    for (size_t i = 0; input[i] != '\0'; i++) {

        if (isspace((unsigned char)input[i])) {

            /* Skip leading whitespace */
            if (!started) {
                continue;
            }

            /* If already in a whitespace run, skip extra whitespace */
            if (in_ws) {
                continue;
            }

            /* First whitespace after a word → write a single space */
            output[j++] = ' ';
            in_ws = 1;

        } else {
            /* Non-whitespace character */
            output[j++] = input[i];
            in_ws = 0;
            started = 1;
        }
    }

    /* Remove trailing space if present */
    if (j > 0 && output[j - 1] == ' ') {
        j--;
    }

    output[j] = '\0';
}

int main(void) {

    const char *s = "   This   is   a   test   string   with         extra   spaces.   ";
    char cleaned[256] = "";  /* Output buffer */

    normalize_whitespace(s, cleaned);

    printf("Original: [%s]\n", s);
    printf("Cleaned:  [%s]\n", cleaned);

    return 0;
}



/*
run:

Original: [   This   is   a   test   string   with         extra   spaces.   ]
Cleaned:  [This is a test string with extra spaces.]

*/

 



answered 2 days ago by avibootz
...