Code of flipped word sequence (c)
Address: http://blog.csdn.net/caroline_wendy
Question: enter an English sentence to flip the order of words in the sentence, but the order of Characters in the word remains unchanged.
FirstFlip (reverse)The entire sentence is then searched for spaces.SpaceTo flip the previous word or encounterTerminator,Same.
Code:
/* * 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;}
Output:
Spike. am I
Programming Algorithm-Flipped word sequence code (c)