据说 C++ STL 函数 substr(pos,n) 的第一个参数 pos 具有这种行为。
"If the position passed is past the end of the string, an out_of_range exception is thrown."
但是,如果我做类似的事情
string s("ab");
cout<<s.substr(2,666)<<endl;
即使 pos=2 根据定义超出了字符串的末尾,也不会抛出异常。
string::end 将“字符串中最后一个字符之后”的位置定义为“超过字符串末尾”。 我注意到返回的字符始终是“\0”。我的问题是这是否是标准行为,我是否可以指望在这种情况下返回空字符串这一事实。谢谢。
最佳答案
实际要求是(§21.4.7.8):
1 Requires: pos <= size()
2 Throws: out_of_range if pos > size().
在你的例子中,pos == size(),所以你永远不会看到异常,并且应该总是得到一个空字符串。
关于c++ - 返回从超过字符串末尾的位置开始的子字符串 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12700662/