如何获得std :: string的尾部? [英] How to get the tail of a std::string?
本文介绍了如何获得std :: string的尾部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取 std :: string
的尾部?
如果愿望成真,它将像这样工作:
If wishes could come true, it would work like that:
string tailString = sourceString.right(6);
但这似乎太简单了,而且行不通...
But this seems to be too easy, and doesn't work...
有什么好的解决方案吗?
Any nice solution available?
可选问题:如何使用Boost字符串算法库?
Optional question: How to do it with the Boost string algorithm library?
添加:
即使原始字符串小于6个字符,也应保存该方法.
The method should be save even if the original string is smaller than 6 chars.
推荐答案
有一个警告需要注意:if substr 被调用,其位置超出了数组的末尾(优于大小),然后抛出 out_of_range
异常.
There is one caveat to be aware of: if substr is called with a position past the end of the array (superior to the size), then an out_of_range
exception is thrown.
因此:
std::string tail(std::string const& source, size_t const length) {
if (length >= source.size()) { return source; }
return source.substr(source.size() - length);
} // tail
您可以将其用作:
std::string t = tail(source, 6);
这篇关于如何获得std :: string的尾部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文