在剑指offer中有这样一道题,将字符串 ABCdefGHI 循环左移3位,也就是以defGHIABC输出
思路:
首先,以pos将字符串分为两组,分别反转这两组字符串,在将整个字符串反转即可得到结果:
反转字符串:
void Swap(string &str,int begin,int end)
{
while(begin<end)
{
swap(str[begin++],str[end--]);
}
}
功能函数:
string Reserve(string str ,int pos )
{
string result= str;
int FirstBegin = 0;
int FirstEnd = pos-1;
int SecondBegin = pos;
int SecondEnd = str.size()-1;
if(pos>0 && pos < str.size()) //输入得合法性
{
Swap(result,FirstBegin,FirstEnd); //反转第一部分
Swap(result,SecondBegin,SecondEnd); //反转第二部分
Swap(result,FirstBegin,SecondEnd); //整体反转
}
return result;
}
实现:
int main()
{
string str;
int pos;
cout << "输入要进行操作得字符串: " << endl;
cin >> str;
cout << "循环左移位数:pos = ";
cin >> pos;
cout<<Reserve(str,pos)<<endl;
return 0;
}
递归的方式实现字符串反转(字符串以’#'结束):
#include <iostream>
using namespace std;
void print()
{
char a;
cin >> a;
if(a != '#') print();
if(a != '#') cout << a;
}
int main(int argc, char *argv[])
{
print();
cout << endl;
return 0;
}