標籤:mystra 編程演算法 翻轉單詞順序 代碼 c
翻轉單詞順序 代碼(C)
本文地址: http://blog.csdn.net/caroline_wendy
題目: 輸入一個英文句子, 翻轉句子中單詞的順序, 但單詞內字元的順序不變.
首先翻轉(reverse)整個句子, 然後尋找空格, 如遇到空格, 則翻轉前面的單詞, 或遇到結束符, 同樣進行翻轉.
代碼:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>#include <string.h>void Reverse(char* pBegin, char* pEnd) {if (pBegin == NULL || pEnd == NULL)return;while (pBegin < pEnd) {char temp = *pBegin;*pBegin = *pEnd;*pEnd = temp;++pBegin, --pEnd;}}char* ReverseSentence(char* pData) {if (pData == NULL)return NULL;char* pBegin = pData;char* pEnd = pData;while (*pEnd != ‘\0‘)pEnd++;pEnd--;Reverse(pBegin, pEnd);pBegin = pEnd = pData;while(*pBegin != ‘\0‘) {if (*pBegin == ‘ ‘) {pBegin++;pEnd++;} else if (*pEnd == ‘ ‘ || *pEnd == ‘\0‘) {Reverse(pBegin, --pEnd);pBegin = ++pEnd;} elsepEnd++;}return pData;}int main(void){char pData[] = "I am a student.";char* result = ReverseSentence(pData);printf("result = %s\n", result);return 0;}
輸出:
result = student. a am I