zoukankan      html  css  js  c++  java
  • 字符串按word反转

    方法一、不用栈

    void reverseChar(char* str, int len)
    {
    	char* q = str+len-1;
    	char* p = str;
    
    	if (!len)
    		return;
    
    	while( p<q )
    	{
    		char tmp = *p;
    		*p = *q;
    		*q = tmp;
    		p++;
    		q--;
    	}
    
    	for (int i=0; i<len; i++)
    		cout << str[i];
    	cout << endl;
    }
    
    void reverseWord(char* str)
    {
    	char* p = str;
    	int count = 0;
    	int total = 0;
    
    	while(1)
    	{
    		p++;
    		count++;
    		total++;
    
    		if ( *p==' ' || *p=='\0' )
    		{
    			reverseChar(p-count, count);
    			//note that, it is -1,not 0
    			count=-1;
    			
    			if ( *p=='\0' )
    			{
    				break;
    			}
    		}
    	}
    
    	reverseChar(str, total);
    }
    

      

    方法二、采用了两个stack,一个用于整个字符串的反转,一个用于保证word内部顺序不变。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    char* reverse_word(char* str)
    {
        stack<char> st;
        stack<char> word;
      
        char* p = str;
      
        st.push('\0');
        while( *p != '\0')
        {
            while( *p == ' ')
                st.push(*p++);
      
            if ( *p == '\0')
                break;
      
            while( *p != '\0' && *p != ' ')
                word.push(*p++);
      
            while( !word.empty() )
            {
                st.push( word.top() );
                word.pop();
            }
        }
      
        p = str;
        while( *p != '\0' )
        {
            *p = st.top();
            st.pop();
            p++;
        }
      
        return str;
    }

     

  • 相关阅读:
    shell脚本批量检查网站是否正常
    测试运维-linux中常用的操作命令以及工作思路
    软件自动化测试工程师面试题集锦(2)
    UI自动化测试常用操作函数(3)
    软件自动化测试工程师面试题集锦(1)
    UI自动化测试常用操作函数(2)
    UI自动化测试常用操作函数(1)
    滑屏找元素
    代码报错解析
    心情20.4.6
  • 原文地址:https://www.cnblogs.com/simonote/p/3095260.html
Copyright © 2011-2022 走看看