本文地址: 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; } else pEnd++; } 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
编程算法 - 翻转单词顺序 代码(C),布布扣,bubuko.com
原文地址:http://blog.csdn.net/caroline_wendy/article/details/37689631