string::npos 速成 及其在自定义split函数中的应用

string::npos的定义:

static const size_t npos = -1;

表示size_t的最大值(Maximum value for size_t)

C++中并没有拆分字符串函数,但是在刷题时经常遇到要拆分字符串的情况, 故编写一个自定义的split函数。

r:egmkang

void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c)
{
  std::string::size_type pos1, pos2;
  pos2 = s.find(c);
  pos1 = 0;
  while(std::string::npos != pos2)
  {
    v.push_back(s.substr(pos1, pos2-pos1));
 
    pos1 = pos2 + c.size();
    pos2 = s.find(c, pos1);
  }
  if(pos1 != s.length())
    v.push_back(s.substr(pos1));
}

参考http://blog.csdn.net/devil_pull/article/details/25478525?utm_source=tuicool&utm_medium=referral

原文地址:https://www.cnblogs.com/AbsolutelyPerfect/p/8410649.html