特性描述及模拟实现strlen、strcpy、strcat、strchr、strstr、strcmp、memcpy、memmove
在学习C语言的过程中,不可避免的会经常接触一些库函数,那么有没有小伙伴想过这些库函数怎么实现的呢?
往往这些库函数都是用最精炼最高效的方式写出的,观摩并模拟出库函数的实现,有利于我们对C语言的深入理解。
今天我将我总结的字符串操作函数及其对应的一些小特性告诉大家,共勉。
特性描述及模拟实现
strlen函数
(测量字符串中到第一个’\0’之前字符的总长度)
特性
//strlen需要目标字符串中有’\0’。
//标准函数库中strlen函数的返回值是size_t类型(也就是无符号整形),也就是unsigned int型。因此在比较两个字符串长度是用到两个strlen相减是不对的。
实现
//非递归
#include <stdio.h>
#include <assert.h>
int my_strlen(const char* str)
{
int count = 0;
assert(str);
while(*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
int ret = my_strlen("hello bit");
printf("%d\n", ret);
return 0;
}
//递归
#include <stdio.h>
#include <assert.h>
int my_strlen(const char* str)
{
assert(str);
if(*str)
return 1 + my_strlen(str + 1);
else
return 0;
}
int main()
{
int ret = my_strlen("hello");
printf("%d\n", ret);
return 0;
}
//指针相减