C++ 实现句子中单词逆序输出

来源:互联网 发布:中国十大网络神兽 编辑:程序博客网 时间:2024/04/28 10:00

        上次有个同事说面试的时候有这样一个上机题,就是把一个句子中的单词逆序输出,应该考的就是字符数组的操作,闲来没事自己把这个小程序写了一遍。

#include "Function.h"#define MAX_CHAR_NUM 255/************************************************************************//* Function:将英文句子中的单词反转输出,如'hello world' 反转后'world hello';/* 注:如果输入语句的前后都有空格,则空格也会在语句中反转如' hello world' 翻转后'world hello '/* Parameter: *pInputSentence将要被反转的句子,支持最大长度为255个字节/* Return: char*  反转后的字符串/************************************************************************/char* ReverseWord(char *pInputSentence){if (NULL == pInputSentence){return NULL;}int len = strlen(pInputSentence);  //获取输入字符串的长度if (MAX_CHAR_NUM - 1 < len)  //转换最大支持数{return NULL;}int index[MAX_CHAR_NUM];  //用来保存空格与字符转变的位置char pOutputSentence[MAX_CHAR_NUM] = {0};int ibegin = 0;  //空格与字符转变的次数index[0] = 0;  //记录输入字符串的第一个字符位置for(int k = 1; k < len; k++){if (pInputSentence[k] == ' ' && pInputSentence[k - 1] != ' ')  //空格转变成字符{ibegin++;index[ibegin] = k;  //记录位置}if (pInputSentence[k] != ' ' && pInputSentence[k - 1] == ' ') //字符转变成空格{ibegin++;index[ibegin] = k;  //记录位置}}ibegin++;index[ibegin] = len;  //记录输入字符串的最后一个字符(\0)的位置int rev = 0;  //输入字符串的字符位置for (int a = ibegin; a > 0; a--){for (int b = index[a - 1]; b < index[a]; b++){pOutputSentence[rev++] = pInputSentence[b];}}pOutputSentence[MAX_CHAR_NUM] = '\0';  //输出字符串最后补上'\0',以防万一return pOutputSentence;}


测试main函数

#include "Function.h"#include <iostream>using namespace std;int main(){char input[] = "You never konw how much you love somebody until she's with other guy";cout << "Before reversing the sentence:" << endl;cout << input << endl;char output[255] = {0};char *pOutput = ReverseWord(input);cout << "After reversing the sentence:" << endl;cout << pOutput << endl;}


0 0
原创粉丝点击