题目1:
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
例如输入字符串"I am a student.",则输出"student. a am I"。
题目2:
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
例如输入字符串"abcdefg"和数字2,左旋转2位得到的结果"cdefgab"。
题目1基本思想:
第一步:翻转句子中的所有字符;
第二步:再翻转每个单词中字符的顺序。
题目2基本思想:
abcdefg和数字2,把前两个字符分到第一部分,把后面的所有字符分到第二部分。
先分别翻转这两部分,结果为bagfedc,接下来再翻转整个字符串即可。
题目1源码:
#include <iostream>
using namespace std;
void reverse(char *pB,char *pE)
{
if(pB==NULL || pE==NULL)
return ;
while(pB<pE)
{
char t=*pB;
*pB=*pE;
*pE=t;
pB++;
pE--;
}
}
char * foo(char *a)
{
if(a==NULL)
return NULL;
char *pB=a;
char *pE=a;
while(*pE!='\0')
pE++;
pE--;
reverse(pB,pE);//翻转整个句子
pB=pE=a;
while(*pB!='\0')
{
if(*pB==' ')
{
pB++;
pE++;
}
else if(*pE==' '|| *pE=='\0')
{
reverse(pB,--pE);
pB=++pE;
}
else
pE++;
}
return a;
}
void main()
{
char a[]="I am a student.";
cout<<foo(a)<<endl;
}
题目2源码:
#include <iostream>
using namespace std;
void reverse(char *pB,char *pE)
{
if(pB==NULL || pE==NULL)
return ;
while(pB<pE)
{
char t=*pB;
*pB=*pE;
*pE=t;
pB++;
pE--;
}
}
char * foo(char *a,int n)
{
if(a!=NULL)
{
int len=strlen(a);
if(len>0&&n>0&&n<len)
{
char * pFS=a;
char * pFE=a+n-1;
char * pSS=a+n;
char * pSE=a+len-1;
reverse(pFS,pFE);//翻转第一部分
reverse(pSS,pSE);//翻转第二部分
reverse(pFS,pSE);//翻转整个
}
}
return a;
}
void main()
{
char a[]="abcdefg";
cout<<foo(a,3)<<endl;
}