当前位置:网站首页>Word inversion implements "suggestions collection"

Word inversion implements "suggestions collection"

2022-07-07 20:59:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack .

As the title , The code is as follows :

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));
	}

}

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116297.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072056575399.html

随机推荐