C++实现翻转单词顺序
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如输入“Iamastudent.”,则输出“student.aamI”。
思路:首先将整个句子按字符翻转,然后再将其中每个单词的字符旋转。
#include<string>
#include"stdafx.h"
voidReverse(char*pBegin,char*pEnd)
{
if(pBegin==NULL||pEnd==NULL)
return;
while(pBegin<pEnd)
{
chartemp=*pBegin;
*pBegin=*pEnd;
*pEnd=temp;
pBegin++,pEnd--;
}
}
char*ReverseSentence(char*pData)
{
if(pData==NULL)
returnNULL;
char*pBegin=pData;
char*pEnd=pData;
while(*pEnd!='\0')
pEnd++;
pEnd--;
//翻转整个句子
Reverse(pBegin,pEnd);
//翻转句子中的每个单词
pBegin=pEnd=pData;
while(*pBegin!='\0')
{
if(*pBegin=='')
{
pBegin++;
pEnd++;
}
elseif(*pEnd==''||*pEnd=='\0')
{
Reverse(pBegin,--pEnd);
pBegin=++pEnd;
}
else
{
pEnd++;
}
}
returnpData;
}
intmain()
{
charinput[]="Iamastudent.";
printf("%s\n\n",input);
printf("Afterreverse.\n\n");
ReverseSentence(input);
printf("%s\n",input);
return0;
}
再给大家分享一段一位国外网友的实现方法
#include<stdio.h>
#include<string.h>
intmain()
{
charstr[50001],ch;
inti,low,high,tmp,len;
while(gets(str))
{
low=0;
high=0;
len=strlen(str);
while(low<len)
{
while(str[low]=='')
{
low++;
}
high=low;
while(str[high])
{
if(str[high]=='')
{
high--;
break;
}
else
{
high++;
}
}
if(str[high]=='\0')
{
high--;
}
tmp=high+1;
while(low<high)
{
ch=str[low];
str[low]=str[high];
str[high]=ch;
low++;
high--;
}
low=tmp;
high=tmp;
}
for(i=len-1;i>0;i--)
{
printf("%c",str[i]);
}
printf("%c\n",str[0]);
}
return0;
}
再来一个小编的代码
#include<iostream>
usingnamespacestd;
voidreverse_part(char*,intpBegin,intpEnd);
voidreverse(char*str)
{
//n为字符串长度
intn=strlen(str)-1;
reverse_part(str,0,n);
intpBegin=0,pEnd=0;
while(str[pEnd+1]){
if(str[pEnd]!=''&&str[pEnd]!='\0')
++pEnd;
//找到空格
else{
reverse_part(str,pBegin,pEnd-1);
//如果下一个还是空格
while(str[pEnd+1]!='\0'&&str[pEnd+1]=='')
++pEnd;
pBegin=++pEnd;
}
}
cout<<str<<endl;
}
voidreverse_part(char*str,intpBegin,intpEnd)
{
chartemp;
for(inti=pBegin;i<=(pEnd-pBegin)/2;++i){
temp=str[i];
str[i]=str[pEnd-i];
str[pEnd-i]=temp;
}
}
voidmain()
{
charstr[]="Iamastudent.";
reverse(str);
system("pause");
}
#include<iostream>
usingnamespacestd;
voidreverse_part(char*,intpBegin,intpEnd);
voidreverse(char*str)
{
//n为字符串长度
intn=strlen(str)-1;
reverse_part(str,0,n);
intpBegin=0,pEnd=0;
while(str[pEnd+1]){
if(str[pEnd]!=''&&str[pEnd]!='\0')
++pEnd;
//找到空格
else{
reverse_part(str,pBegin,pEnd-1);
//如果下一个还是空格
while(str[pEnd+1]!='\0'&&str[pEnd+1]=='')
++pEnd;
pBegin=++pEnd;
}
}
cout<<str<<endl;
}
voidreverse_part(char*str,intpBegin,intpEnd)
{
chartemp;
for(inti=pBegin;i<=(pEnd-pBegin)/2;++i){
temp=str[i];
str[i]=str[pEnd-i];
str[pEnd-i]=temp;
}
}
voidmain()
{
charstr[]="Iamastudent.";
reverse(str);
system("pause");
}
以上就是解决单词顺序翻转的3种方法了,希望小伙伴们能够喜欢