您的位置:首页 > 其它

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

2015-09-04 13:44 477 查看
细节:

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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: