Rewrite the strlen, strlen, and sizeof functions in string. h.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.