翻转句子中单词的顺序 C语言
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。
为简单起见,标点符号和普通字母一样处理。
比如将“I am a student”转化为"student a am I"。
#include <stdio.h> #include <string.h> //逆转字符串 char* Reverse(char *str, int len) { if(str == NULL || len <= 0) return str; char *pLast = str + len - 1; char *pBegin = str; while(pBegin < pLast) { char temp = *pBegin; *pBegin = *pLast; *pLast = temp; ++ pBegin; -- pLast; } return str; } //逆转句子 char * ReverseSentence(char *str) { if(str == NULL) { return str; } //逆转整个句子 Reverse(str, strlen(str)); //逆转各个单词 char *pBegin = str; char *pEnd = str; while(*pEnd != '\0') { while(*pEnd != '\0' && *pEnd != ' ') ++pEnd; //逆转单词 Reverse(pBegin, pEnd - pBegin); if(*pEnd == '\0') { break; } ++pEnd; pBegin = pEnd; } return str; } int main() { char str1[] = ""; char str2[] = "a"; char str3[] = "abc"; char str4[] = "I am a student"; if(strcmp(ReverseSentence(str1), "") == 0 || strcmp(ReverseSentence(str2), "a") == 0 || strcmp(ReverseSentence(str3), "abc") == 0 || strcmp(ReverseSentence(str4), "student a am I") == 0 ) { printf("reverse sentence ok\n"); } return 0; }