码迷,mamicode.com
首页 > 其他好文 > 详细

单词反转实现

时间:2015-06-02 21:56:13      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

如题,代码如下:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!