模拟实现长度受限制的字符串函数(strncpy、strncat、strncmp)
2017-07-30 10:15
579 查看
根据以上可知,在有的情况下,长度不受限制的字符串函数已经不能满足我们的需求,因此,便需要一些长度受限制的字符串函数,来满足我们的需要。
长度受限制的字符串函数,可以根据我们的需求,给指定的长度,从而完成我们的需求。
先看这些函数的原型:
根据以上原型,现在模拟实现这些函数,从而加强对这些函数的理解。
模拟实现库函数,不仅有利于我们对这些函数的理解,更有利用我们今后的学习。
长度受限制的字符串函数,可以根据我们的需求,给指定的长度,从而完成我们的需求。
先看这些函数的原型:
char *strncat( char *strDest, const char *strSource, size_t count );
int strncmp( const char *string1, const char *string2, size_t count );
char *strncpy( char *strDest, const char *strSource, size_t count );
根据以上原型,现在模拟实现这些函数,从而加强对这些函数的理解。
**//strncat字符串追加**
char *my_strncat(char *pdest, const char *pstr, size_t n) { assert(pdest!= NULL); assert(pstr != NULL); char *ret = pdest; while (*pdest != '\0')//找目标空间的'\0' { pdest++; } while ((*pstr != '\0') && (n-->0))//拷贝字符串到目标空间 { *pdest = *pstr; *pdest++; *pstr++; } if (n-- < 0) { *pdest = 0; } return ret; } int main() { char arr[20] = "hello "; char*p = "world"; my_strncat(arr, p,6); printf("%s\n", arr); system("pause"); return 0; }
**//模拟实现strncmp(字符串比较)**
int my_strncmp(const char *string1, const char *string2, size_t n) { assert(string1 != NULL); assert(string2 != NULL); while ((*string1 == *string2) && (n-- >= 0)) { string1++;//如果相等,则一直向后比较 string2++; } if ((*string1 != *string2)) { return *string1 - *string2; } //如果两者不相等,则利用ascll值返回 } int main() { char *arr1 = "abcdef"; char *arr2 = "abchdz"; int ret = my_strncmp(arr1, arr2,3); printf("%d\n", ret); system("pause"); return 0; }
**//模拟实现strncpy(字符串拷贝)**
char*my_strncpy(char* pdest, const char*psrc,size_t n) { char *ret = pdest; assert(pdest); assert(psrc); while ((*psrc != NULL) && n-->0) { *pdest = *psrc; pdest++; psrc++; } if (*psrc != NULL) { *pdest = 0; } return ret; } int main() { int *arr = "abcdef"; int buf[20] = { 0 }; my_strncpy(buf, arr,2); printf("%s\n", buf); system("pause"); return 0; }
模拟实现库函数,不仅有利于我们对这些函数的理解,更有利用我们今后的学习。
相关文章推荐
- 模拟输出受限制的字符串函数-strncat,strncmp,strncpy
- 字符串函数模拟实现之strcpy、strncpy、strcmp、strncmp、strcat、strncat
- 模拟实现strncpy,strncat,strncmp
- c语言中部分限制字符函数的实现strncmp,strncat,strncpy,strstr,strrstr
- 模拟实现strcpy 模拟实现strncpy 模拟实现strcat 模拟实现strncat 模拟实现strcmp 模拟实现strncmp 模拟实现memcpy 模拟实现memmove
- 模拟实现strcmp,strncmp,strstr,strcat,strncat,strcpy,strncpy,strlen ,memcpy,memmove等函数
- [C语言]模拟实现strcpy/strncpy/strcat/strncat/strcmp/strncmp/strstr
- 模拟实现strncpy ,模拟实现strncat ,模拟实现strncmp
- 模拟实现strcpy,strncpy,strcat,strncat,strcmp,strncmp
- 模拟实现C库函数strncpy、strncat、strncmp
- 模拟实现strncpy,strncat,strncmp
- 模拟实现C库函数:strncpy、strncat和strncmp
- 模拟实现//strcpy //strncpy //strcat //strncat //strcmp //strncmp //memcpy //memmove
- 模拟实现strcpy,strncpy,strcat,strncat,strcmp,strncmp,memcpy,memmove
- 模拟实现strncpy,strncat,strncmp
- 模拟实现strncpy,strncat,strncmp
- 字符串函数(strlen、strcmp、strcat、strncat、strncpy、strncmp、strchr、strrchr、strpbark、strstr、strspn、strcspn等)
- 《c程序设计语言》读书笔记-5.5-指针实现strncpy,strncat,strncmp
- C语言~模拟实现strncpy、strncat、strncmp函数
- 《c程序设计语言》读书笔记-5.5-指针实现strncpy,strncat,strncmp