#include /* For strlen. */ #include /* For "malloc". */ #include /* For "isspace" */ #include /* This takes "word" and strips leading and trailing spaces from it, returning the result in allocated memory. For convenience, if the word has no leading or trailing spaces, it just duplicates the word. */ static char * strip_spaces (const char * word) { int l; int n; const char * word_begins; const char * word_ends; l = strlen (word); n = l; word_begins = word; while (isspace (*word_begins)) { word_begins++; n--; } word_ends = word + l - 1; while (isspace (*word_ends)) { word_ends--; n--; } if (n == l) { return strdup (word); } else { char * copy; int i; copy = malloc (n + sizeof ((char) '\0')); if (! copy) { fprintf (stderr, "Out of memory.\n"); exit (EXIT_FAILURE); } for (i = 0; i < n; i++) { copy[i] = word_begins[i]; } copy[n] = '\0'; return copy; } } int main () { const char * examples[] = { " now ", "\t\tis ", "the", "winter\n\n\n", " of ", "\n\nour\t\t", "discontent.", }; int n_examples; int i; n_examples = sizeof (examples) / sizeof (examples[0]); for (i = 0; i < n_examples; i++) { char * trimmed; trimmed = strip_spaces (examples[i]); printf ("<%s> -> <%s>\n", examples[i], trimmed); /* Because the word is always duplicated, we don't need to think about whether to free it or not. */ free (trimmed); } return 0; }