C strlen & C ++ strlen

Source: Internet
Author: User

Let's take a look at the following examples:

/* Define data */

...
Char * msg1 = "testtest ";
Char * msg2 = "test ";
Int Len = 20, T = 1;
...

1 -----> If (strlen (msg2)> = strlen (msg1)... // right

2 -----> If (strlen (msg2)-strlen (msg1)> = 0)... // "error"

3 -----> If (strlen (msg2)> = 10)... // right

4 -----> If (strlen (msg2)-10> = 0)... // "error"

5 -----> If (strlen (msg2)-len> = 0)... // "error"

6 -----> If (t-strlen (msg2)> = 0)... // "error"

7 -----> If (T> = strlen (msg2)... // right

The "error" we mentioned here does not mean a syntax error. All syntaxes are correct, and compilation and running are successful. The "error" here indicates that this statement cannot work as expected. The results of these four statements are always true.

Why?

Let's first look at the prototype of the library function strlen:

Size_t strlen (char const * string );

Note that strlen returns a value of Type size_t. What type is size_t? This type is defined in the header file stddef. H. It is an unsigned integer type. When the problem arises, the use of the unsigned number in the expression may lead to unpredictable consequences.

When there are signed and unsigned types in the expression, all operands are automatically converted to the unsigned type. The calculation result of the unsigned number cannot be negative. Therefore, the results of the four statements, 2, 4, 5, and 6, will always be true.

In this case, you either use the Form 1, 3, 7, or forcibly convert the strlen return value to int.

 

 

String type cannot use strlen () for length. strlen only applies to all char * types.

If required, first convert the string type to the char * type and use the c_str () function to convert it.

# Include <iostream>
# Include <string>

Using namespace STD;

Int main ()
{

String STR = "fjaljjfj ";

Int Len;

Len = strlen (Str. c_str ());

Cout <Len <Endl;

Return 0;

}

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.