Si je lis la quête correctement et que vous voulez faire vous-même, sans utiliser boucle je pense avoir une solution (sssuming UTF-8) et je pense c'est une façon conforme et portable de codage URL chaînes de requête :
#include <boost/function_output_iterator.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>
namespace {
std::string encimpl(std::string::value_type v) {
if (isalnum(v))
return std::string()+v;
std::ostringstream enc;
enc << '%' << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << int(static_cast<unsigned char>(v));
return enc.str();
}
}
std::string urlencode(const std::string& url) {
// Find the start of the query string
const std::string::const_iterator start = std::find(url.begin(), url.end(), '?');
// If there isn't one there's nothing to do!
if (start == url.end())
return url;
// store the modified query string
std::string qstr;
std::transform(start+1, url.end(),
// Append the transform result to qstr
boost::make_function_output_iterator(boost::bind(static_cast<std::string& (std::string::*)(const std::string&)>(&std::string::append),&qstr,_1)),
encimpl);
return std::string(url.begin(), start+1) + qstr;
}
il n'a pas de dépendances non standard autres que si vous boost et n'aimez pas le coup de pouce dépendance, il est pas difficile à enlever.
Je l'ai testé à l'aide:
int main() {
const char *testurls[] = {"http://foo.com/bar?abc<>de??90 210fg!\"$%",
"http://google.com",
"http://www.unicode.com/example?großpösna"};
std::copy(testurls, &testurls[sizeof(testurls)/sizeof(*testurls)],
std::ostream_iterator<std::string>(std::cout,"\n"));
std::cout << "encode as: " << std::endl;
std::transform(testurls, &testurls[sizeof(testurls)/sizeof(*testurls)],
std::ostream_iterator<std::string>(std::cout,"\n"),
std::ptr_fun(urlencode));
}
qui tout semblait fonctionner:
http://foo.com/bar?abc<>de??90 210fg!"$%
http://google.com
http://www.unicode.com/example?großpösna
Devient:
http://foo.com/bar?abc%3C%3Ede%3F%3F90%20%20%20210fg%21%22%24%25
http://google.com
http://www.unicode.com/example?gro%C3%9Fp%C3%B6sna
avec ces carrés qui examples
n'est pas UTF8 unicode? – maxschlepzig
UTF-8 est l'un des protocoles de transfert de données Unicode. Il a l'avantage d'être rétrocompatible avec le codage ASCII. +1 pour la suggestion de GJ. – ivymike
@maxschlepzig: Je le pensais aussi. Mais appris quelque chose de nouveau aujourd'hui ... –