讲一句话里的单词进行倒置如,“I am a student” 转换为“student a am I”
有两种方法,一种是先全部倒置,如上述讲倒置为“tneduts a ma I”,再讲空格作为分隔,每个倒置;
另一种是先按空格倒置,再整体倒置;
第一种实现代码:
#include <iostream>
#include <string>
using namespace std;
void RevStr(char *src)
{
int j=0;
int i=0;
int begin,end;
char temp;
j=strlen(src)-1;
while(j>i)
{
temp=src[i];
src[i]=src[j];
src[j]=temp;
i++;
j--;
}
i=0;
while (src[i]!='\0')
{
if(src[i]!=' ')
{
begin = i;
while ((src[i]!='\0')&&(src[i]!=' '))
{
i++;
}
i=i-1;
end = i;
}
while (end>begin)
{
temp=src[begin];
src[begin]=src[end];
src[end]=temp;
begin++;
end--;
}
i++;
}
}
int main ()
{
char sec[]="I am a student.";
cout<<sec<<endl;
RevStr(sec);
cout<<sec<<endl;
return 0;
}