Springe zum Inhalt

UrlEncode von std::string

inline unsigned char toHex(const unsigned char x) {
	return x > 9 ? (x + 'A' - 10) : (x + '0');
}
 
std::string URLEncode(const std::string &sIn)
{
	std::string sOut;
 
	const size_t length = sIn.length();
	for (size_t idx = 0; idx < length;) {
		const char ch = sIn.at(idx);
		if (isalnum(ch))
		{
			sOut.append(1, ch);
		}
		else if (isspace(ch) && ((ch != '\n') && (ch != '\r')))
		{
			sOut.append(1, '+');
		}
		else
		{
			sOut.append(1, '%');
			sOut.append(1, toHex(ch>>4));
			sOut.append(1, toHex(ch%16));
		}
		idx++;
	}
	return sOut;
}