c++ string split

cplusplus上介绍了很多种方法
stack overflow 上有个很简短的方法

下面两种方法会漏掉空字符串,比如127.0.0.1.,最后一个空字符串会漏掉

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

static string& strip(string& s, const string& chars = " ")
{
        s.erase(0, s.find_first_not_of(chars.c_str()));
        s.erase(s.find_last_not_of(chars.c_str()) + 1);
        return s;
}

static void split(const string& s, vector<string>& tokens, const string& delimiters = " ")
{
        string::size_type lastPos = s.find_first_not_of(delimiters, 0);
        string::size_type pos = s.find_first_of(delimiters, lastPos);
        while (string::npos != pos || string::npos != lastPos) {
                tokens.push_back(s.substr(lastPos, pos - lastPos));
                lastPos = s.find_first_not_of(delimiters, pos);
                pos = s.find_first_of(delimiters, lastPos);
        }
}

static void parse(string& s, map<string,string>& items)
{
        vector<string> elements;
        s.erase(0, s.find_first_not_of(" {"));
        s.erase(s.find_last_not_of("} ") + 1);
        split(s, elements, ",");
        for (vector<string>::iterator iter=elements.begin(); iter != elements.end(); iter++) {
                vector<string> kv;
                split(*iter, kv, ":");
                if (kv.size() != 2) continue;
                items[strip(kv[0], " \"")] = strip(kv[1], " \"");
        }
}

int
main()
{
        string data = "  {  \"key1\"  :  \"data1\"  ,  \"key2\"  :  \"data2\"    }  ";
        map<string,string> items;
        parse(data, items);

        for (map<string,string>::iterator iter=items.begin(); iter != items.end(); iter++) {
                cout << "key=" << (*iter).first << ",value=" << (*iter).second << endl;
        }
}

对于比较简单的分割可以使用std::getline, 以71. 简化路径为例

class Solution {
public:
    string simplifyPath(string path) {
        stringstream ss(path);
        vector<string> tmp;
        string s;
        // 按照 '/' 分隔
        while (getline(ss, s, '/')) {
            //   /./    //
            if (s == "." || s == "") continue;
            if (s == "..") {
                if (!tmp.empty()) {
                    tmp.pop_back();
                }
            }
            else {
                tmp.push_back(s);
            }
        }
        string ans;
        for (const auto& e : tmp) {
            ans += "/";
            ans += e;
        }
        if (ans.empty()) ans = "/";
        return ans;
    }
};

这样写不会漏掉空字符串

vector<string> split(string s, string spliter) {
    vector<string> ans;
    size_t it = 0;
    size_t pos = 0;
    while ((it = s.find(spliter, pos)) && it != s.npos) {
        ans.push_back(s.substr(pos, it - pos));
        pos = it + spliter.size();
    }
    ans.push_back(s.substr(pos, s.size() - pos));
    return ans;
}
posted @ 2021-12-03 10:04  miyanyan  阅读(534)  评论(0编辑  收藏  举报