给定一个不包含标点符号的字符串,如何按单词将该字符串逆序
思路分析:一共分两个步骤,第一步先按单词逆序,第二步将整个句子逆序。
代码如下:
#include "stdafx.h" #include <stdio.h> void ReverseWord(char* p, char* q) { while (p < q) { char t = *p; *p = *q; *q = t; p++; q--; } } char* Reverse(char *s) { char *p = s; char *q = s; while (*q != '\0') { if (*q == ' ') { ReverseWord(p, q - 1); q++; p = q; } else q++; } ReverseWord(p, q - 1); ReverseWord(s, q - 1); return s; } int main() { char a[] = "I am glad to see you"; printf("%s\n", Reverse(a)); getchar(); return 0; }
效果如图: