字符串处理函数的实现及注意事项

细节:

1、一定要对地址要加非0断言const常量。

assert宏的原型定义在<assert.h>中,原型定义:

#include <assert.h>
void assert( int expression );

        assert的作用是计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。


2、为了实现链式表达式操作,所以返回目的地址。

        例如 int length = strlen( strcpy( strDest, “hello world”) );

     

3、'\0'和NULL转程整型都是0,但其类型是不同的'\0'是字符,NULL 为(void *)0 是指针。

      判断字符串结尾时,用'\0'判断指针,用NULL。不要混用。


4、如何遍历字符串。另外,一定要注意指针的位置。

      代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

int strlen(const char * str)
{
	assert(str != NULL);
	int n = 0;
	while((*str++) != '\0')
	//while(*str++)
		++n;
	return n;
}

char *strcpy(char * dst,const char *src)
{
	assert(dst != NULL && src != NULL);
	char *sdst = dst;
	//while((*dst++ = *src++) != '\0');
	while(*dst++ = *src++);
	return sdst;
}

char *strcat(char *dst, const char *src)
{
	assert(dst != NULL && src != NULL);
	char * sdst = dst;
	//while(*dst)
	//    dst++;
	while(*dst++);
	      dst--;//注意‘\0’字符,所以要减去1
	//while((*dst++ = *src++) != '\0');
	while(*dst++ = *src++);
	return sdst;
}

void *memcpy(void *dst,const void *src,size_t n)
{
	assert((dst != NULL) && (src != NULL)); 
	char *pdst = (char *)dst;
	const char *psrc = (char *)src;
	while(n--)
		*pdst++ = *psrc++;
	return pdst;
}

void *memmove(void *dst,const void *src,size_t n)
{
	assert((dst != NULL) && (src != NULL)); 
	char *pdst = (char *)dst;
	const char *psrc = (char *)src;
	if(pdst + n < psrc || pdst > psrc +n)
	{
		//没有内存重叠,从前向后拷贝
		while(n--)
			*pdst++ = *psrc++;
	}
	else
	{
		//有内存重叠,逆序拷贝
		pdst = pdst + n - 1;
		psrc = psrc + n - 1;
		while(n--)
			*pdst-- = *psrc--;
	}
	return pdst;
}


int main()
{
	char p[20] = "tfytest!";
	int n = strlen(p);
	printf("n = %d \n",n);
	char src[5] = "haha";
	char sr[] = "yyy";
	//strcpy(p,sr);
	//printf("%s \n",p);
	strcat(p,src);
	printf("strcat test:%s \n",p);

	memcpy(p,src,sizeof(src));
	printf("--------------------------\n memcpy test:%s \n",p);
	memmove(p,src,sizeof(src));
	printf("--------------------------\n memmoves test:%s \n",p);
	system("pause");
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值