目录
1.计数器
#define _crt_secure_no_warnings
#include <stdio.h>
#include <assert.h>
#pragma warning(disable:4996)
int my_strlen(char const* str)
{
int count = 0;
assert(str); //声明,防止arr传过来空指针,需要包含头文件 #include <assert.h>
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char arr[] = "abcdef";
int len = my_strlen(arr);
printf("%d\n", len);
return 0;
}
2.递归
递归的特点是:它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解。
递归的主要思考方式在于:把大事化小。
在模拟实现strlen函数中,若是遇到字符'\0',则返回0,否则,返回1+my_strlen(指针+1),且指针会越来越趋近于’\0‘。
#define _crt_secure_no_warnings
#include <stdio.h>
#include <assert.h>
#pragma warning(disable:4996)
int my_strlen(char const* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
else
{
return 1 + my_strlen(str + 1);
}
}
int main()
{
char arr[] = "abcdef";
int len = my_strlen(arr);
printf("%d\n", len);
return 0;
}
3.指针-指针
#define _crt_secure_no_warnings
#include <stdio.h>
#include <assert.h>
#pragma warning(disable:4996)
int my_strlen(char const* str)
{
char* p = str;
assert(str);
int i = 0;
while (*p != '\0')
{
p++;
}
return p - str;
}
int main()
{
char arr[] = "abcdef";
int len = my_strlen(arr);
printf("%d\n", len);
return 0;
}
注:指针-指针的绝对值是指针和指针之间元素的个数。指针-指针,计算的前提条件是两个指针指向的是同一块空间。