Skip to content

Instantly share code, notes, and snippets.

@junpeitsuji
Last active December 10, 2015 14:58
Show Gist options
  • Save junpeitsuji/4450714 to your computer and use it in GitHub Desktop.
Save junpeitsuji/4450714 to your computer and use it in GitHub Desktop.
Split the HTTP GET query string into the parameters.
#include <map>
#include <string>
#include <iostream>
using namespace std;
/**
* Split the HTTP GET query string into the parameters.
*
* e.g.
* input = "test1=12345&test2=56789"
* output = {
* "test1" => "12345",
* "test2" => "56789"
* }
*
* @args query - query string.
* @return result - Hash map key and values.
*
* @author Junpei Tsuji (@tsujimotter)
* @lastupdate 2013/01/04
*
*/
map<string, string> query_parser(const string &query)
{
string str = query;
map<string, string> result;
int cutAt;
while( (cutAt = str.find_first_of("&")) != str.npos )
{
if(cutAt > 0)
{
string entry = str.substr(0, cutAt);
int c;
if( (c = entry.find_first_of("=")) != entry.npos )
{
string key = entry.substr(0, c);
string value = entry.substr(c + 1);
result.insert( map<string, string>::value_type( key, value ) );
}
}
str = str.substr(cutAt + 1);
}
if(str.length() > 0)
{
int c;
if( (c = str.find_first_of("=")) != str.npos )
{
string key = str.substr(0, c);
string value = str.substr(c + 1);
result.insert( map<string, string>::value_type( key, value ) );
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment