#include #include #include #include static const char* get_next_word(const char* pstart, const char* p, size_t* len) { const char* pend; while (p >= pstart && isspace(*p)) --p; if (p < pstart) return NULL; pend = p-- + 1; while (p >= pstart && !isspace(*p)) --p; *len = pend - ++p; return p; } static void reverseWords( const char* instr, /* in: string of words */ char* outstr) /* out: reversed words */ /* (caller must ensure big enough) */ { const char* p = instr + strlen(instr) - 1; size_t len; if ((p = get_next_word(instr, p, &len)) == NULL) { *outstr = '\0'; return; } memcpy(outstr, p, len); outstr += len; while ((p = get_next_word(instr, --p, &len)) != NULL) { *outstr++ = ' '; memcpy(outstr, p, len); outstr += len; } *outstr = '\0'; return; } int main() { char instr[256]; char outstr[256]; strcpy(instr, " one two \t three four "); reverseWords(instr, outstr); printf("in='%s' out='%s'\n", instr, outstr); return 0; }