大家好,又见面了,我是全栈君。
如题,代码例如以下:
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)); } }
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/116297.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...