//字符串倒序輸出 Iput: Love you, No reason Output: reason No, you Love #include <iostream> #include <algorithm> #include <cassert> #include <cctype> using namespace std; void ReverseString(char *const str, const int len); void ReverseAllWord(char *str); int main() { char str[] = "Love you, No reason"; ReverseAllWord(str); cout << str << endl; return 0; } void ReverseString(char *const str, const int len) { if(str == NULL || len < 2) return; for(int i=0; i<(len/2); i++) { swap(str[i], str[len-i-1]); } } void ReverseAllWord(char *str) { assert(str != NULL); ReverseString(str, strlen(str)); cout << str << endl; char *word_start = str; char *word_end = str; char *temp = str; while(*temp) { if(isalpha(*temp)) { word_start = temp; word_end = temp; while(isalpha(*word_end)) word_end++; int word_len = word_end - word_start; ReverseString(word_start, word_len); temp += (word_len-1); } temp++; } }
先將這個字符串倒序,然後將每個單詞還原(再次倒序)。