您的位置:首页 > 其它

翻转句子中单词的顺序

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

举例:输入"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;
}


运行界面如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐