1.strlen 函数模拟实现
strlen 函数介绍
声明
参数
str 是字符串的地址
返回值
返回‘\0’之前的字符串长度
模拟实现
首先获取到字符串的地址,
然后对地址解引用判断是否是‘\0’,
如果是,则返回count的值
如果不是,则count自增1。
size_t my_strlen(const char*str)
{
//计数
size_t count = 0;
while (*str)//当*str‘\0’时,循环结束
{
str++;
count++;
}
return count;
}
int main()
{
char str[] = { "abcdef" };
size_t ret = my_strlen(str);
printf("%d", ret);
return 0;
}
2.strcpy的模拟实现
strcpy的介绍
声明
参数
destination指向要复制内容的目标数组的指针。
source 要复制的 C 字符串。
返回值
返回destination
模拟实现
char* my_strcpy(char* destination, char* source)
{
//先将destination存起来,方便后面返回destination
char* tmp = destination;
//复制
while (*source)
{
*destination = *source;
destination++;
source++;
}
//如果source的长度小于destination,将destination其余元素转换成‘\0’
if (*destination != '\0')
{
*destination = '\0';
}
}
int main()
{
char destination[50] = { "abcde" };
char source[] = { "fgh" };
my_strcpy(destination, source);
printf("%s", destination);
return 0;
}
3.strcat的模拟实现
声明
参数
destination指向目标数组的指针,该数组应包含 C 字符串,并且足够大以包含连接的结果字符串
source要附加的 C 字符串。
返回值
返回destination
模拟实现
char* my_strcat(char* destination, char* source)
{
//找到destination的'\0'
while (*destination)
{
destination++;
}
//追加
while (*source)//遇到‘\0’终止循环
{
*destination = *source;
destination++;
source++;
}
}
int main()
{
char destination[50] = { "abcde" };//为了能存下要追加的字符串,开辟50个空间大小
char source[] = { "fghij" };
my_strcat(destination, source);
printf("%s", destination);
return 0;
}
4.strcmp的模拟实现
声明
参数
str1被比较的字符串
str2被比较的字符串
返回值
模拟实现
int my_strcmp(char* str1, char* str2)
{
while (*str1 && *str2)
{
if (*str1 - *str2 > 0)
return 1;
else
return -1;
}
if (*str1 != 0)
return 1;
else
return -1;
}
int main()
{
char str1[] = { "abcde" };
char str2[] = { "abcdf" };
int ret=my_strcmp(str1, str2);
printf("%d", ret);
return 0;
}