【C语言】模拟实现strncpy、strncat、strncmp函数
2016-08-01 16:05
417 查看
strncpy、strncat、strncmp函数与strcpy、strcat、strcmp函数非常相近,在实现功能上也十分接近。但是在“str…”函数里,它是用自身的字符数组长度来判断循坏的停止条件,在一些情况下这是不安全的,比如在strcat函数,我们给arr追加arr时,程序就会崩溃。所以,用自身的长度来作为循环停止条件是不安全的。
于是出现了这么一群“strn…”函数,它们在函数拷贝的过程中,将‘\0’也拷贝出来,并且以‘\0’作为循环的终止条件,这样子就会避免程序找不到结束条件,自己崩溃的现象。所以,在这种情况,代码和之前实现那几个函数在大的模块上几乎没有什么改动,在判断条件上需要判断。
1.strncpy
2.strncat
3.strncmp
模拟实现函数,最重要的就是理解这个函数的工作原理,明白要实现的功能。在没有头绪的时候,不妨多举几个例子去模拟一下这个函数,理解后动笔写也会更加容易。
于是出现了这么一群“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"); }
模拟实现函数,最重要的就是理解这个函数的工作原理,明白要实现的功能。在没有头绪的时候,不妨多举几个例子去模拟一下这个函数,理解后动笔写也会更加容易。
相关文章推荐
- 模拟实现C语言strncpy.strncat.strncmp函数
- 模拟实现C语言strncpy.strncat.strncmp函数
- C语言~模拟实现strncpy、strncat、strncmp函数
- [C语言]模拟实现strcpy/strncpy/strcat/strncat/strcmp/strncmp/strstr
- C语言模拟实现strncpy、strncpy、strncat、strstr和strrstr函数实现
- 【c语言】模拟实现strcat()、strncat()函数
- 【面试题】C语言:模拟实现strncpy,尝试比较strncpy与strcpy区别。
- 模拟实现strcmp,strncmp,strstr,strcat,strncat,strcpy,strncpy,strlen ,memcpy,memmove等函数
- [置顶] 【C语言】 实现strncpy,strncat,strncmp
- 【面试题】C语言:模拟实现strncpy,尝试比较strncpy与strcpy区别。
- C语言模拟实现strcpy、strncpy、strcmp、strcat、strstr
- C语言模拟实现strncpy、strcat
- 【C语言】【笔试题】模拟实现strncat
- 模拟实现长度受限制的字符串函数(strncpy、strncat、strncmp)
- 模拟实现strncpy ,模拟实现strncat ,模拟实现strncmp
- 模拟实现strncpy,strncat,strncmp
- 【C语言】【面试题】【笔试题】模拟实现strncpy
- 模拟实现strcpy 模拟实现strncpy 模拟实现strcat 模拟实现strncat 模拟实现strcmp 模拟实现strncmp 模拟实现memcpy 模拟实现memmove
- 字符串函数模拟实现之strcpy、strncpy、strcmp、strncmp、strcat、strncat
- c语言中部分限制字符函数的实现strncmp,strncat,strncpy,strstr,strrstr