用三种方式实现该功能
实现这个函数必须明白函数库中 strlen 函数的一些细节,最重要的一点是对该函数返回值的描述,我未能上传截图,我将取自 MSDN 中对该函数返回值的描述粘贴到这里(Each of these functions returns the number of characters in string, excluding the terminal NULL. No return value is reserved to indicate an error.),供大家参考。
#include<stdio.h>
#include<windows.h>
#include<assert.h>
int my_strlen(const char *str) //计数器方式
{
int count = 0;
assert(str);
while(*str++){
count++;
}
return count;
}
int my_strlen(const char *str) //递归方式
{
assert(str);
if(*str == '\0'){
return 0;
}
else
return (1 + my_strlen(str+1));
}
int my_strlen(const char *str) //指针 - 指针的方式
{
char *start = str;
char *end = start;
while(*end){
end++;
}
return end - start;
}
int main()
{
char *string = "1234abcd";
int len = my_strlen(string);
printf("len = %d\n",len);
system("pause");
return 0;
}
第二种方式的独特之处在于不需要创建临时变量。
第三种方式中,指针 - 指针在常规情况下,当两个指针指向同一内存空间(数组)时,二者相减即为二者之间元素的个数。