对于strlen:我们想必是不陌生的,熟悉的。话不多说,直接上代码
前言
strlen函数可以求字符串的长度,同时我们通过模拟实现字符串可以提高我们对字符串的理解以及运用
一、strlen 的定义
Get string length
Returns the length of the C string str.
The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
This should not be confused with the size of the array that holds the string. For example:char mystr[100]="test string";
defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.
In C++, char_traits::length implements the same behavior.
二、使用步骤
1.引入库
代码如下(示例):
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
assert(str);
char* start = str;
char* end = str;
while (*end != '\0')
{
end++;
}
return end - start;
}
int main()
{
char arr[] = "abcdef";
int len = my_strlen(arr);
printf("%d\n", len);
}
总结
对于模拟实现strlen,我们首先要明白strlen 的定义以及基本的用法,strlen返回的是size_t, 而size_t的本质是typedef unsigned(即无符号的整型)