华北计算所其中一道机试题,逆转字符串,但是单词顺序不变

来源:互联网 发布:东吴证券网上交易软件 编辑:程序博客网 时间:2024/04/29 13:34

/*
华北计算所其中一道机试题,逆转字符串,但是单词顺序不变,字符串中只含有字母和空格。

比如this is a book,逆序后为book a is this
Author:shizhixin
Email:szhixin@gmail.com
Blog:http://blog.csdn.net/ShiZhixin
Data:Oct 25,2009
*/

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
//初步版本,记得面试时候这么写的,但是开始有点问题,指针移动的时候
// void InverseStr(char* cpStrOutput,char* cpStrInput,int length)
// {
//     int nAllCount=0;//当前处理的总字母的个数
//     for (int i=0;i<length;i++)
//     {
//         int nLetterCount=0;//计算单个单词的字母个数
//         const char* temp=cpStrInput;
//         while(*cpStrInput!=' ' && *cpStrInput!='/0') //机试好像也忘记判断/0的情况了
//         {
//             nLetterCount++;
//             cpStrInput++;
//             i++;
//         }
//         if (*cpStrInput!='/0')//记得机试的错误主要在这里当时紧张这都没调试出来,没有这个的话,他一直处在cpStrInput空格位置了
//         {
//             cpStrInput++;
//         }
//         nAllCount+=nLetterCount;
//         for (int j=0;j<nLetterCount;j++)
//         {
//             cpStrOutput[length-nAllCount+j]=*temp;//temp很不专业!
//             temp++;
//         }
//         if (*temp!='/0')//不加判断的话,最后一个单词length-nAllCount-1成为-1了,所以main中delete时出现错误!   
//         {
//             cpStrOutput[length-nAllCount-1]=*temp;       
//         }
//         nAllCount++;
//         temp++;
//     }
//     cpStrOutput[length]='/0';
// }

// 输入参数为const类型,
void InverseStr(char* cpStrOutput,const char* cpStrInput,int length)
{
    const char* pMove=cpStrInput; //另设两个变量移动指针
    const char* pGetValue=cpStrInput;
    int nAllCount=0;//当前处理的总字母的个数,这里不用这个变量,直接用当前处理的i
    for (int i=0;i<length;i++)
    {
        int nLetterCount=0;//计算单个单词的字母个数
        while(*pMove!=' ' && *pMove!='/0')
        {
            nLetterCount++;
            pMove++;
            i++;
        }
        if (*pMove!='/0')
        {
            pMove++;
        }
        for (int j=0;j<nLetterCount;j++)
        {
            cpStrOutput[length-i+j]=*pGetValue;
            pGetValue++;
        }
        if (*pGetValue!='/0')
        {
            cpStrOutput[length-i-1]=*pGetValue;
        }
        pGetValue++;
    }
    cpStrOutput[length]='/0';
}

int main(int argc, char* argv[])
{
    char* strInput="My blog is blog.csdn.net/shizhixin";
    int nLen=strlen(strInput);
    char* strOutput=new char[nLen+1];
    InverseStr(strOutput,strInput,nLen);
    cout<<strOutput<<endl;
    if (strOutput!=NULL) //记得机试的时候也没释放内存,这么低级的错误,艾,考试就蒙了
    {
        delete[] strOutput;   
        strOutput=NULL;
    }       
    return 0;
}

原创粉丝点击