标签:style blog http color io os ar strong sp
本文地址: http://blog.csdn.net/caroline_wendy
题目: 输入一个英文句子, 翻转句子中单词的顺序, 但单词内字符的顺序不变.
首先翻转(reverse)整个句子, 然后查找空格, 如遇到空格, 则翻转前面的单词, 或遇到结束符, 相同进行翻转.
代码:
/* * main.cpp * * Created on: 2014.9.19 * Author: spike */ #include <iostream> #include <vector> #include <climits> #include <cstring> 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
标签:style blog http color io os ar strong sp
原文地址:http://www.cnblogs.com/gcczhongduan/p/3994159.html