About the string member function substr

Source: Internet
Author: User
The prototype of this function is substr (size_type off, size_type count)

The first parameter indicates the offset in the string char array. Count is the length of the string starting from the offset.

The incorrect use of these two parameters will cause crash or incorrect results.

There are two major errors: off is greater than the array length or less than 0, and count is greater than the string length or count is less than 0

For the off error, when it is greater than the length of the array, that is, the array out-of-bounds error, the program crash.
When the provided off is less than 0, the parameter type is unsigned int, so it will be forced to convert off into a large integer, which leads to an out-of-bounds error and program crash.

For the Count error, when count + off is greater than the length of the array, substr first checks whether it exceeds the length of the array. If it exceeds the length, it will be processed according to the maximum subscript of the array. Therefore, it is equivalent to substr (Off, String. Size ()-off );

Similarly, when count is less than 0, it is converted to a large integer, and the result is equivalent to substr (Off, String. Size ()-off );

In summary, when using this function, you must pay attention to the input parameters to prevent program crash or get incorrect results.

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.