Function prototype: size_t strlen (const char * Str)
Return Value: returns the number of characters in the string, excluding the terminator '/0 '. If no return value is returned, an error occurs;
Parameter description: Str: string with '/0' as the Terminator.
Function implementation:
Size_t strlen (const char * Str)
{
Assert (null! = Str );
Const char * TMP = STR;
For (; TMP! = ''; ++ TMP)
;
Return TMP-STR;
}
Note: differences between strlen and sizeof:
Strlen is used to calculate the number of characters in a string, while sizeof is used to calculate the number of bytes occupied by the variable.
Use a few examples for comparison (Win32 platform ):
Char ch [20] = "ABCD ";
Char * P = CH;
Char * SZ = "ABCDE ";
Char STR [] = "AB ";
Then:
Strlen (CH) = 4; sizeof (CH) = 20;
Strlen (p) = 4; sizeof (p) = 4; // P is a pointer, which occupies 4 bytes, so sizeof (p) = 4
Strlen (sz) = 5; sizeof (sz) = 4; // P is a pointer, which occupies 4 bytes, so sizeof (p) = 4
Strlen (STR) = 2; sizeof (STR) = 3; // when strlen is used to evaluate the string length, the terminator '/0' is not included, while the sizeof is included.
In short, we must always grasp one thing: strlen calculates the number of characters, and sizeof calculates the number of bytes occupied by the variable.