字符串处理函数的实现及注意事项
2015-09-04 13:44
477 查看
细节:
1、一定要对地址要加非0断言和const常量。
assert宏的原型定义在<assert.h>中,原型定义:
assert的作用是计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
2、为了实现链式表达式操作,所以返回目的地址。
例如 int length = strlen( strcpy( strDest, “hello world”) );
3、'\0'和NULL转程整型都是0,但其类型是不同的'\0'是字符,NULL 为(void *)0 是指针。
判断字符串结尾时,用'\0'。判断指针,用NULL。不要混用。
4、如何遍历字符串。另外,一定要注意指针的位置。
代码:
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"); }
相关文章推荐
- At KFC, we do chicken right!翻译过来是什么?
- JAVA文件中获取路径及WEB应用程序获取路径方法
- hdu3518 Boring counting(后缀数组)
- 函数对象与仿函数(function object and functor)
- IE6 IE8下背景图片不显示问题
- 【POJ 3657】Haybale Guessing
- Leetcode -- Single Number
- 限制 root 远程登录的方法
- MyBatis传入多个参数的问题
- linux入门教程(七) linux系统用户以及用户组管理
- 蓝懿iOS零基础学习之旅 感谢刘国斌老师
- Win10使用高分辨率和大尺寸显示器字体模糊如何解决?
- JAVA获得当前tomcat的服务路径
- topcoder ExerciseMachine
- hdu 3853 概率dp
- objective-C编程 对象的类型和动态绑定摘要
- iOS coreData和MagicalRecord如何分页
- JavaScript 开发者必备的10款 SublimeText 插件
- 数据库索引
- java基本数据类型与包装类型