#include <iostream>
#include <map>
#include <string>
#include <vector>
std::string TestCookie{"ID=1; TT=2\r\n"};
void SplitCookie(std::string_view Cookie) {
int err = 0;
std::vector<std::string> items;
std::map<std::string, std::string> values;
std::string CookieString{Cookie};
CookieString.erase(std::remove_if(CookieString.begin(), CookieString.end(),
[](char c) -> bool {
if (c == '\r' || c == '\n' || c == ' ')
return true;
return false;
}),
CookieString.end());
size_t lastpos = 0;
while (lastpos < CookieString.length()) {
size_t curpos = CookieString.find(';', lastpos);
if (curpos == std::string::npos) {
if (lastpos < CookieString.length())
items.push_back(CookieString.substr(lastpos));
break;
}
items.push_back(CookieString.substr(lastpos, curpos - lastpos));
lastpos = curpos + 1;
}
for (auto &item : items) {
size_t pos = item.find('=');
if (pos == std::string::npos) {
err = -1;
break;
}
if (pos == 0 || pos == item.length() - 1) {
err = -2;
break;
}
std::string name{item.substr(0, pos)};
std::string value{item.substr(pos + 1)};
if (values.find(name) != values.end()) {
err = -3;
break;
}
values[name] = value;
}
if (err != 0)
values.clear();
}
int main(int argc, char *argv[]) {
SplitCookie(TestCookie);
return 0;
}
分离Cookie各条目
由
·
发表回复