URL Encoding

URL-encodes string. This algorithm is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.



									/*****Please include following header files*****/
// string
/***********************************************/

/*****Please use following namespaces*****/
// std
/*****************************************/

static string DecimalToHexadecimal(int dec) {
	if (dec < 1) return "0";

	int hex = dec;
	string hexStr;

	while (dec > 0)
	{
		hex = dec % 16;

		if (hex < 10)
			hexStr = hexStr.insert(0, string(1, (char)(hex + 48)));
		else
			hexStr = hexStr.insert(0, string(1, (char)(hex + 55)));

		dec /= 16;
	}

	return hexStr;
}

static string EncodeURL(string data) {
	string result;

	for each (char c in data)
	{
		if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9'))
		{
			result += c;
		}
		else
		{
			result += '%';

			string s = DecimalToHexadecimal(c);

			if (s.length() < 2)
				s = s.insert(0, "0");

			result += s;
		}
	}

	return result;
}
								


Example

									string data = "jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^";
string value = EncodeURL(data);
								


Output

									jdfgsdhfsdfsd%206445dsfsd7fg%2F%2A%2F%2Bbfjsdgf%25%24%5E