strlen():求字符串长度
size_t strlen( const char *string );
- 字符串以'\0'作为结束标志,strlen函数返回的是在字符串中‘\0’前面出现的字符的个数(不包括'\0')。
- 参数指向的字符串必须要以‘\0’结束。
- 注意函数的返回值为size_t,是无符号的(易错)
模拟实现:
1:计数器
//
//计数器方式:
//
int my_strlen(const char* str)//const:防止类型声明的类型或者函数形参的类型发生变化。防止变量的类型发生变化;
{
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
2:函数递归
//
//2:函数递归方式
//
int my_strlen(const char* str)
{
if (*str == '\0')
return 0;
else
return 1 + my_strlen(str + 1);
}
3:指针-指针
//
//3:指针-指针方式
//
int my_strlen(const char* str)
{
char* p = str;
while (*p != '\0')
{
p++;
}
return p - str;
}
#include <stdio.h>
//
//计数器方式:
int my_strlen(const char* str)//const:防止类型声明的类型或者函数形参的类型发生变化。防止变量的类型发生变化;
{
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
//
//2:函数递归方式
//
//int my_strlen(const char* str)
//{
// if (*str == '\0')
// return 0;
// else
// return 1 + my_strlen(str + 1);
//}
//
//3:指针-指针方式
//
//int my_strlen(const char* str)
//{
// char* p = str;
// while (*p != '\0')
// {
// p++;
// }
// return p - str;
//}
int main()
{
char arr[] = "abcdef";
printf("字符串长度为:%d",my_strlen(arr));
return 0;
}