先翻转整个字符串,再翻转每个单词。
#include <string.h>
void swap(char *left, char *right){
char tmp = *left;
*left = *right;
*right = tmp;
}
void reverse(char *str, int begin, int end){
while(begin < end){
swap(&str[begin], &str[end]);
++begin;
--end;
}
}
void reverseSentence(char *sentence){
int len = strlen(sentence);
int wordBegin = 0;
int wordEnd = 0;
if(sentence == NULL) return;
reverse(sentence, 0, len - 1);
while(sentence[wordBegin] == ' '){
++wordBegin;
++wordEnd;
}
while(sentence[wordEnd] != '\0'){
while(sentence[wordEnd] != ' ' && sentence[wordEnd] != '\0'){
++wordEnd;
}
reverse(sentence, wordBegin, wordEnd - 1);
if(sentence[wordEnd] == '\0') break;
wordBegin = wordEnd;
while(sentence[wordBegin] == ' '){