输入:第一个字符串: "This is fishsky 's Chinese site: http://www.fishsky.com.cn/cn"
子串: "fishsky"
输出: "nc/nc.moc.fishsky.www//:ptth :etis esenihC s'fishsky si sihT"
一般的方法是先扫描一边第一个字符串,然后用stack把它反转,同时记录下子串出现的位置。然后再扫描一遍把记录下来的子串再用stack反转。我用的方法是用一遍扫描数组的方法。扫描中如果发现子串,就将子串倒过来压入堆栈。
最后再将堆栈里的字符弹出,这样子串又恢复了原来的顺序。
====================================
#include <iostream>
#include <stack>
#include <assert.h>
using namespace std;
const char* Reverse(const char*str,const char* substr)
{
assert(str && substr);
stack<char> stack1;
const char* psubstr = substr,*head = str, *rear = str;
while(*head != '/0')
{
while(*head != '/0' && *psubstr == *head)
{
psubstr++;
head++;
}
if(*psubstr == '/0')
{
const char* p;
for(p=head-1;p>=rear;p--)
stack1.push(*p);
psubstr = substr;
rear = head;
}
else
{
stack1.push(*rear);
head = ++rear;
psubstr = substr;
}
}
char *return_str = new char[strlen(str)+1];
int i = 0;
while(!stack1.empty())
{
return_str[i++] = stack1.top();
stack1.pop();
}
return_str[i] = '/0';
return return_str;
}
char* Reverse1(const char*str,const char*substr)
{
stack<char> stack1;
int len = strlen(str);
char *temp = new char[len+1];
const char *psubstr = substr;
strcpy(temp,str);
//遍历一遍字符串
for(int i=0;i<len;i++)
{
int j = 0; //j是指向substr的下标
//如果找到第一个开始循环
while(str[i] == substr[j] && substr[j] != '/0') //temp
{
j++;
i++;
}
//j超过了substr的长度了,说明找到了
if(j == strlen(substr))
{
j--; //substr的下标减去1
for(;j>=0;j--)
stack1.push(substr[j]); //temp
i--;
}
else
stack1.push(str[i]); //temp
}
int k = 0;
while(!stack1.empty())
{
temp[k++] = stack1.top();
stack1.pop();
}
temp[k] = '/0';
return temp;
}
int main(int argc,char* argv[])
{
char *str = "This is fishsky 's Chinese site: http://www.fishsky.com.cn/cn";
cout<<str<<endl;
//cout<<Reverse(str,"fishsky")<<endl;
cout<<Reverse1(str,substr)<<endl;
return 0;
}
(二) 用库函数
#include <iostream>
#include <string.h>
using namespace std;
void strDeal(char*str,char*sunbtr)
{
char *start,*end,*ptr;
ptr = start = str;
while(*ptr++)
;
end = ptr-2;
while(start<end)
swap(*start++,*end--);
cout<<str<<endl;
char *temp = strrev(strdup(sunbtr));
ptr = str;
while(*ptr)
{
start = strstr(ptr,temp);
if(!start)
break;
end = start+strlen(sunbtr)-1;
ptr = start+strlen(sunbtr);
while(start<end)
swap(*start++,*end--);
}
cout<<str<<endl;
}
int main()
{
char *str = "This is fishsky 's Chinese site: http://www.fishsky.com.cn/cn";
strDeal(str,"fishsky");
return 0;
}