您的位置:首页 > 其它

以单词为单位,对字符串进行反转

2009-09-08 12:22 465 查看
要求以单词为单位进行字符串的反转,代码如下:

还有人家写的几个编程题:http://www.zhuxinquan.com/cn/cat-48/

// WordReverse.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdlib.h"
#include "string.h"

char* CharReverse(const char*, int);
char *WordReverse(const char *,int);

int _tmain(int argc, _TCHAR* argv[])
{
char * p = "I am student";
char * d = WordReverse(p,12);
return 0;
}

// 以单词反转
char *WordReverse(const char *strSource,int strLen)
{
char *strWord = CharReverse(strSource, strLen);
char *strDes = (char *) malloc(sizeof(char) * strLen);
char *temp = strDes;
int startPos = 0; // 记录单词开始反转的位置
for(int i = 0; i < strLen + 1; i++)
{
if( strWord[i] == ' ' | strWord[i] == '\n') //如果遇到空格反转上一个单词
{
for(int j = i - 1; j >= startPos; j--)
*strDes++ = strWord[j];

if(strWord[i] == '\n') //判断trWord最后一个单词
*strDes++ = '\n';
else
*strDes++ = ' ';
startPos = i + 1;
}
}
return temp;
}
// Reverse the entire string
char *CharReverse(const char * strSource, int strLen)
{
char *strDes  = (char *) malloc(sizeof(char) * strLen);
char * temp = strDes;
for(int i = strLen -1; i >= 0; i--)
{
*strDes++ = strSource[i];
}
*strDes++ = '\n';
return temp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: