• 单词反转实现


    如题,代码例如以下:

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

  • 相关阅读:
    C语言宏中"#"和"##"的用法
    Ubuntu 14.04 LTS 安装和配置Bochs
    C和C++中static的比较
    总线设备驱动模型
    驱动设计的思想:面向对象/分层/分离
    基于分层思想的驱动程序软件框架
    单元测试指南
    Apollo移植
    剑指offer python版 数组中出现次数超过一半的数字
    剑指offer python版 字符串的排列
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5135360.html
Copyright © 2020-2023  润新知