模拟实现C语言strncpy.strncat.strncmp函数
2016-05-28 18:35
387 查看
在C语言string这个库中的strcpy,strcat,strcmp这三个函数是通过传递数组的内容来限制它们的,这样做并不是一个好方法,所以新增了strncpy,strncat,strncmp这三个函数,用传参的方式现实字符串的改变长度,模拟实现如下:
strncpy函数:char* my_strncpy(char*dest, const char*src, int n)
{
assert(dest);
assert(src);
char*p = dest;
while (n--)
{
*p++ = *src++;
}
*p = 0;
return dest;
}strncat函数:char* my_strncat(char*dest, const char*src, int n)
{
assert(dest);
assert(src);
char*p = dest;
while (*p)
{
p++;
}
while (n--)
{
*p++ = *src++;
}
*p = 0;
return dest;
}strncmp函数:int my_strncmp(const char*str1, const char*str2, int n)
{
assert(str1);
assert(str2);
while (n--)
{
if (*str1 == *str2)
{
str1++;
str2++;
}
else
{
if ((*str1-*str2)<0)
return -1;
else
return 1;
}
}
return 0;
} 这三个函数的主要思想无非就是利用n进行循环,不让字符串本身的内容作为循环限制条件,无疑这样做提高了语言的安全性。
如有不足之处希望批评指正,有什么看不懂的,也希望留言= =。
strncpy函数:char* my_strncpy(char*dest, const char*src, int n)
{
assert(dest);
assert(src);
char*p = dest;
while (n--)
{
*p++ = *src++;
}
*p = 0;
return dest;
}strncat函数:char* my_strncat(char*dest, const char*src, int n)
{
assert(dest);
assert(src);
char*p = dest;
while (*p)
{
p++;
}
while (n--)
{
*p++ = *src++;
}
*p = 0;
return dest;
}strncmp函数:int my_strncmp(const char*str1, const char*str2, int n)
{
assert(str1);
assert(str2);
while (n--)
{
if (*str1 == *str2)
{
str1++;
str2++;
}
else
{
if ((*str1-*str2)<0)
return -1;
else
return 1;
}
}
return 0;
} 这三个函数的主要思想无非就是利用n进行循环,不让字符串本身的内容作为循环限制条件,无疑这样做提高了语言的安全性。
如有不足之处希望批评指正,有什么看不懂的,也希望留言= =。
相关文章推荐
- C语言中指针与函数的关联2(数组的降级)
- C语言中的指针与数组的关联1
- C语言模拟实现memcpy,memmove函数
- C语言中模拟实现strcpy,strstr,strcat函数
- C语言实现数组的奇偶排序
- c语言不定参数与printf函数的实现
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- leetcode_350 Intersection of Two Arrays II
- leetcode_349 Intersection of Two Arrays
- (C++)使用模板在编译期计算阶乘
- c++上级实验6--数组合并
- C++线索化二叉树
- c# 调用c++带有回调函数方法的实现
- C++/CLI托管编程专业名词(部分)
- C++虚函数与函数的执行顺序
- 注意!C语言的枚举enum是int型常量
- C/C++默认浮点型
- C++多重继承
- mysql C++(1)
- VC++获取系统信息/获取OS/获取MAC/获取本地IP/判断是否为网吧