翻转单词顺序 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 输入一个英文句子, 翻转句子中单词的顺序, 但单词内字符的顺序不变.
首先翻转(reverse)整个句子, 然后查找空格, 如遇到空格, 则翻转前面的单词, 或遇到结束符, 相同进行翻转.
代码:
/*
* main.cpp
*
* Created on: 2014.9.19
* Author: spike
*/
#include
#include
#include
#include
using namespace std;
void Reverse(char* begin, char* end) {
if (begin == NULL || end == NULL)
return;
while(begin < end) {
char tmp = *begin;
*begin++ = *end;
*end– = tmp;
}
}
char* ReverseWords(char* data) {
if (data == NULL) return NULL;
int len = strlen(data);
char* begin = data;
char* end = &data[len-1];
Reverse(begin, end);
begin = end = data;
while(*begin != ‘\0’) {
if (*begin == ‘ ‘) {
begin++;
end++;
} else if (*end == ‘ ‘ || *end == ‘\0’) {
Reverse(begin, –end);
begin = ++end;
} else {
++end;
}
}
return data;
}
int main(void)
{
char data[] = “I am Spike.”;
char* res = ReverseWords(data);
cout << res << endl;
return 0;
}
输出:Spike. am I