反转字符串(指定子串不反转)
代码摘抄自 c和c++程序员面试秘籍
#include "stdafx.h" #include <string> #include <stack> #include <cassert> #include <iostream> using namespace std; const char *str_reverse(const char* s1,const char *token) { stack<char> stack1; const char *ptoken=token; const char *head=s1; const char *rear=s1; assert(s1&&token); while(*head!='\0') { while(*head!='\0'&&*ptoken==*head) { ptoken++; head++; } if (*ptoken=='\0') //逆序将子串token压入栈 { const char *p; for (p=head-1;p>=rear;p--) { stack1.push(*p); } ptoken=token; //保证了如果s1中出现多个token时程序也能正确输出 rear=head; } else //顺序将s1压入堆 { stack1.push(*rear++); head=rear; ptoken=token; } } char *pReturn=new char[strlen(s1)+1]; int i=0; while(!stack1.empty()) { pReturn[i++]=stack1.top(); //顺序出栈 stack1.pop(); } pReturn[i]='\0'; //结束符 return pReturn; } int _tmain(int argc, _TCHAR* argv[]) { char s1[]="welcome you,my friend you here"; char token[]="you"; const char* p=str_reverse(s1,token); cout<<s1<<endl; cout<<p<<endl; return 0; }
代码逻辑很好