#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.]
*/