【C语言】模拟实现strncpy、strncat、strncmp函数
来源:互联网 发布:微博来自mac客户端 编辑:程序博客网 时间:2024/05/01 14:10
strncpy、strncat、strncmp函数与strcpy、strcat、strcmp函数非常相近,在实现功能上也十分接近。但是在“str…”函数里,它是用自身的字符数组长度来判断循坏的停止条件,在一些情况下这是不安全的,比如在strcat函数,我们给arr追加arr时,程序就会崩溃。所以,用自身的长度来作为循环停止条件是不安全的。
于是出现了这么一群“strn…”函数,它们在函数拷贝的过程中,将‘\0’也拷贝出来,并且以‘\0’作为循环的终止条件,这样子就会避免程序找不到结束条件,自己崩溃的现象。所以,在这种情况,代码和之前实现那几个函数在大的模块上几乎没有什么改动,在判断条件上需要判断。
1.strncpy
char* my_strncpy(char *des,const char *src,int count){ char *cp=des; assert(src && des); while(count && (*des++=*src++)) { count--; } if(count>0) { while(--count) { *des++='\0'; } } return cp;}int main(){ char string[80]={0}; int len=strlen("hello"); printf( "String = %s\n", my_strncpy(string,"Hello",len)); system("pause"); return 0;}
2.strncat
char* strncat(char *des,const char *src,int count){ char *cp=des; assert(src && des); while(*des!='\0') { *dest++; } while(count && *src) { *des++=*src++; count--; } *des='\0'; return cp;}int main() { char arr[20] = "hello"; int len = strlen(arr); char *ret = my_strncat(arr,arr, len); printf("%s", ret); system("pause"); return 0; }
3.strncmp
int my_strncmp(const char *arr1,const char *arr2,int count){ assert(arr1 && arr2); while(count && (*arr1==*arr2)) { if(arr1=='\0') return 0; arr1++; arr2++; count--; } return *arr1-*arr2;}int main(void){ char *arr1 = "abcd"; char *arr2 = "abcde"; int len=strlen(arr1); int ret= my_strncmp(arr1, arr2,len); printf("%d\n",ret); system("pause");}
模拟实现函数,最重要的就是理解这个函数的工作原理,明白要实现的功能。在没有头绪的时候,不妨多举几个例子去模拟一下这个函数,理解后动笔写也会更加容易。
0 0
- 模拟实现C语言strncpy.strncat.strncmp函数
- 【C语言】模拟实现strncpy、strncat、strncmp函数
- 【C语言】模拟实现strncpy strncat strncmp strchr strrchr函数
- C语言~模拟实现strncpy、strncat、strncmp函数
- 模拟实现C库函数strncpy、strncat、strncmp
- 【C语言】 实现strncpy,strncat,strncmp
- 模拟实现strncpy,strncat,strncmp
- 模拟实现strncpy,strncat,strncmp
- 模拟实现strncpy,strncat,strncmp
- 模拟实现strncpy,strncat,strncmp
- 模拟实现 strncpy strncat strncmp strchr strrchr 函数
- 模拟实现C库函数:strncpy、strncat和strncmp
- [C语言]模拟实现strcpy/strncpy/strcat/strncat/strcmp/strncmp/strstr
- c语言中部分限制字符函数的实现strncmp,strncat,strncpy,strstr,strrstr
- 模拟实现strncpy ,模拟实现strncat ,模拟实现strncmp
- C语言模拟实现strncpy、strncpy、strncat、strstr和strrstr函数实现
- 模拟输出受限制的字符串函数-strncat,strncmp,strncpy
- 模拟实现strcmp,strncmp,strstr,strcat,strncat,strcpy,strncpy,strlen ,memcpy,memmove等函数
- HDU Problem 5326 Work 【并查集】
- fatal error: unexpectedly found nil while unwrapping an Optional value
- 各种行程问题
- Apache POI(3):给Excel文件添加打开密码
- JAVA基础问答(一)
- 【C语言】模拟实现strncpy、strncat、strncmp函数
- getAttribute()与getParameter的区别
- DBUnit 对比数据的4种方式
- fill_parent/match_parent/wrap_content区别
- 菜鸟运维
- C语言读取的结束方法及getchar()和putchar(int)、gets
- 杭电1856More is better
- 与用户沟通定位bug时需求问的问题
- ViewPager与百度地图的滑动冲突