The returned substring, starting from the position after the end of the line (C ++)

The first parameter of the C ++ STL function substr (pos, n), pos, has this behavior.

"If the position passed past the end of the line, an out_of_range exception is thrown."

However, if I do something like

string s("ab"); cout<<s.substr(2,666)<<endl; 

then no exception is thrown even if pos = 2 is by definition located beyond the end of the line.

The string :: end defines the position "after the last character in the string" as "minus the end of the string". I noticed that the returned character is always "\ 0". My question is that this is standard behavior, and if I can expect that in this case an empty string is returned. Thanks.

+4
source share
2 answers

Actual requirement (ยง21.4.7.8):

 1 Requires: pos <= size() 2 Throws: out_of_range if pos > size(). 

In your case, pos == size (), so you should never see an exception and should always have an empty string.

+3
source

Since the character at the position passed as the first parameter is included in the result, position 2 should not be considered past after the end of the line: it is at the end of the line. The length of the string is the legal argument for going to substr .

+1
source

Source: https://habr.com/ru/post/1437497/


All Articles