![](/img/trans.png)
[英]How to get a reference to the tail of a tuple from an object std::tuple<Head,Tail…>
[英]How to get the tail of a std::string?
如何检索std::string
的尾部?
如果愿望成真,那就可以这样:
string tailString = sourceString.right(6);
但这似乎太容易了,而且不起作用......
有什么好的解决方案?
可选问题:如何使用Boost字符串算法库?
添加:
即使原始字符串小于6个字符,该方法也应该保存。
有一点值得注意:如果使用超出数组末尾的位置调用substr (优于大小),则抛出out_of_range
异常。
因此:
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);
使用substr()
方法和字符串的size()
,只需获取它的最后一部分:
string tail = source.substr(source.size() - 6);
对于处理小于尾部大小的字符串的情况,请参阅Benoit的答案 (并且赞成它,我不明白为什么我得到7个upvotes而Benoit提供更完整的答案!)
你可以这样做:
std::string tailString = sourceString.substr((sourceString.length() >= 6 ? sourceString.length()-6 : 0), std::string::npos);
请注意, npos
是默认参数,可能会被省略。 如果您的字符串的大小超过6,则此例程将提取整个字符串。
这应该这样做:
string str("This is a test");
string sub = str.substr(std::max<int>(str.size()-6,0), str.size());
甚至更短,因为subst的字符串结束为第二个参数的默认值:
string str("This is a test");
string sub = str.substr(std::max<int>(str.size()-6,0));
您可以使用迭代器来执行此操作:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char *line = "short line for testing";
// 1 - start iterator
// 2 - end iterator
string temp(line);
if (temp.length() >= 8) { // probably want at least one or two chars
// otherwise exception is thrown
int cut_len = temp.length()-6;
string cut (temp.begin()+cut_len,temp.end());
cout << "cut is: " << cut << endl;
} else {
cout << "Nothing to cut!" << endl;
}
return 0;
}
输出:
cut is: esting
由于您还要求使用boost库的解决方案:
#include "boost/algorithm/string/find.hpp"
std::string tail(std::string const& source, size_t const length)
{
boost::iterator_range<std::string::const_iterator> tailIt = boost::algorithm::find_tail(source, length);
return std::string(tailIt.begin(), tailIt.end());
}
请尝试以下方法:
std::string tail(&source[(source.length() > 6) ? (source.length() - 6) : 0]);
string tail = source.substr(source.size() - min(6, source.size()));
尝试使用substr方法。
我认为,使用迭代器是C ++方式
像这样的东西:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
std::string tail(const std::string& str, size_t length){
string s_tail;
if(length < str.size()){
std::reverse_copy(str.rbegin(), str.rbegin() + length, std::back_inserter(s_tail));
}
return s_tail;
}
int main(int argc, char* argv[]) {
std::string s("mystring");
std::string s_tail = tail(s, 6);
cout << s_tail << endl;
s_tail = tail(s, 10);
cout << s_tail << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.