C++ String --- 你可能不知道的一些用法

一些工具

C++ std::string --- 你可能不知道的一些用法

ref1

策略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()

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章