Empty check with string split

感情迁移 提交于 2019-12-02 08:29:13

How about boost? I think it is easiest way to split string.

#include <algorithm>
#include <iterator>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;

int main()
{
    string s("f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=");

    vector<string> v1;    
    split(v1, s, is_any_of("&"), token_compress_on); 
    copy(v1.begin(), v1.end(), ostream_iterator<string>(cout, "\n"));    

    for (auto i : v1) {
        vector<string> v2;
        split(v2, i, is_any_of("="), token_compress_on); 

        copy(v2.begin(), v2.end(), ostream_iterator<string>(cout, "\n===\n"));
    }
}

Check whether the last character of the string you're tokenising is in fact the seperator itself.

while (p != NULL && p[strlen(p) - 1] != *sep)


Edit: Based on your comment, then before tokenising the string I would modify it using string::find and string::replace to replace occurrences of "=&" with "=hi&" and a terminating "=" with "=hi". In that way you'll avoid awkward parsing.

Also, then you won't need two passes of the tokenising because the strDelimit parameter of strtok can then be "&=" (both delimiters in one pass).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!