标签:
如题,代码如下:
void reverse_words(std::string& original) { enum { scan_normal, scan_frag, } state; char buf[4]; memset(buf, 0, sizeof(buf)); int last = original.size() - 1; int cur = original.size() - 1; int n = original.size(); char* p = &original.front(); // scan ptr char* movep = p; // move ptr state = scan_normal; int wfrag_len = 0; int wlen = 0; int movel = n; int scan_ok; while (n > 0) { scan_ok = 1; int end_frag = 0; wfrag_len = 0; // scan word until ' ' or word size >= word_buf while (p[cur] != ' ') { --cur; if ( (wfrag_len = (last - cur)) >= sizeof(buf) ) { scan_ok = 0; if (scan_normal == state) { state = scan_frag; } break; } } if (state == scan_normal) wlen = wfrag_len; else wlen += wfrag_len; movel = n - wfrag_len; if (movel <= 0 || n <= wlen) break; if (scan_ok) { if (state == scan_frag) { state = scan_normal; end_frag = 1; } } if (wfrag_len > 0) { memcpy(buf, p + cur + 1, wfrag_len); memmove(p + wfrag_len + scan_ok - end_frag, p, movel - (scan_ok - end_frag)); if (end_frag) memmove(p + wlen, p + wlen - 1, n - wlen); memcpy(p, buf, wfrag_len); } else { // skip empty memmove(p + wlen + 1, p + wlen, movel - wlen - 1); } if (scan_normal == state) { p[wlen] = ' '; p += (wlen + 1); n -= (wlen + 1); cur = last = (n - 1); } else { // scan_frag cur = last; } if (scan_ok || end_frag) wlen = 0; memset(buf, 0x0, sizeof(buf)); } }
标签:
原文地址:http://blog.csdn.net/xseekerj/article/details/46335217