测试题02

怎样倒序排列一个字符串是我们很多时候需要的。此文在于抛砖引玉奋斗

首先,我们要给出一个长度够用的字符串指针(dest)。

然后,递减这个指针到0。在递减的过程中,dest累加而我们预设的字符串累减。这种方式是指针标准操作方式。

我使用了预设字符串指针地址+这个字符串长度变量这种方式(因为递减长度也是在递减)。

第二种方式,就是使用数组。

代码如下:

#include "stdafx.h"
#include <string.h>
#include <stdlib.h>


int _tmain(int argc, _TCHAR* argv[])
{
	char *src = "hello,world";
	int len = strlen(src);

	char *dest = NULL;
	dest = (char *)malloc(len + 1);
	// dest = (char *)malloc(len + 1); // standard: 要为'\0'分配一个空间

	char *d = dest;
	// char *s = &src[len - 1];        // standard: 指向最后一个字符

    /* One way */
	while (len-- != 0) {
		*d++ = *(src + len);           // one way
		//*d++ = *s--;                 // standard: 
	}

	*d = 0;                            // standard: 尾部要加0
	/* Two way */
	/*
	int i = 0;
	while (len-- != 0) {
		dest[i] = src[len];            // two way
		i++;
	}
    */
	printf("%s\n", dest);

	free(dest);                        // standard:  使用完,应当释放空间,以免造成内存汇泄露

	return 0;
}


本文代码在VS2005调试通过。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值