翻转句子中单词的顺序

时间:2023-01-08 11:43:21

题目:输入一个英文句子,翻转句子中单词的顺序,但单词内的字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和简单字母一样处理。

举例:输入"I am a student.",则输出"student. a am I"。

答:每个单词先自我翻转,然后整个句子翻转。

#include "stdafx.h"
#include
<iostream>
#include
<string>

using namespace std;

/*
翻转
I am a student. --> student. a am I

*/

void swap(string *str, int begin, int end)
{
while (begin < end)
{
char ch = str->at(begin);
str
->at(begin) = str->at(end);
str
->at(end) = ch;
begin
++;
end
--;
}
}

void Reverse(string *str)
{
int length = str->size();
if (NULL == str || length <= 0)
{
return;
}
int begin = -1;
int end = -1;
for (int i = 0; i < length; i++)
{
if (-1 == begin && str->at(i) == ' ')
{
continue;
}
if (-1 == begin)
{
begin
= i;
}
if (str->at(i) == ' ')
{
end
= i - 1;
}
else if (i == length - 1)
{
end
= length - 1;
}
else
{
continue;
}
swap(str, begin, end);
begin
= -1;
end
= -1;
}
swap(str,
0, length - 1);
}

int _tmain(int argc, _TCHAR* argv[])
{
char chArr[100] = {"I am a student."};
string str(chArr);
cout
<<str<<endl;
Reverse(
&str);
cout
<<str<<endl;
return 0;
}

运行界面如下:

翻转句子中单词的顺序