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

     

  • 相关阅读:
    java8 Date/Time API 新的日期处理工具
    java8 Lambda 表达式和函数式接口快速理解
    java8 新特性精心整理(全)
    Git 从入门到熟练|不敢说精通
    C# Color 列表
    自动控制原理6
    forfiles命令详解
    详解SQLEXPR32_x86_CHS.exe、SQLEXPR_x86_CHS.exe、SQLEXPR_x64_CHS.exe之间的区别
    power disiagner pdb
    vs 中大括号之间垂直虚线显示
  • 原文地址:https://www.cnblogs.com/simonote/p/3095260.html
Copyright © 2011-2022 走看看