C++ std::string --- 你可能不知道的一些用法
策略1 use boost lib
#include <boost/algorithm/string/predicate.hpp>
if (boost::starts_with(argv[1], "--foo="))
策略2 區間匹配
Using STL this could look like:
std::string prefix = "--foo=";
std::string arg = argv[1];
if (std::equal(prefix.begin(), prefix.end(), arg.begin())) {
std::istringstream iss(arg.substr(prefix.size()));
iss >> foo_value;
}
策略3 截取匹配
Code I use myself:
std::string prefix = "-param=";
std::string argument = arg[1];
if(argument.substr(0, prefix.size()) == prefix) {
std::string argumentValue = argument.substr(prefix.size(), argument.size());
}
策略4
Use std::mismatch
. Pass in the shorter string as the first iterator range and the longer as the second iterator range. The return is a pair of iterators, the first is the iterator in the first range and the second, in the second rage. If the first is end of the first range, then you know the the short string is the prefix of the longer string e.g.
std::string foo("foo"); // 甲
std::string foobar("foobar"); // 甲乙
auto res = std::mismatch(foo.begin(), foo.end(), foobar.begin());
if (res.first == foo.end())
{
// foo is a prefix of foobar.
}
// for short
std::mismatch(s1.begin(),s1.end(),s2.begin()).first==s1.end()