简介本文介绍一个C++代码片段:C++字符串通过URL编码,感兴趣的朋友可以参考一下。

C++字符串通过URL编码

string urlEncode(const string& URL)
{
	string result = "";
	for (unsigned int i = 0; i<URL.size(); i++)
	{
		char c = URL[i];
		if (
			('0' <= c && c <= '9') ||
			('a' <= c && c <= 'z') ||
			('A' <= c && c <= 'Z') ||
			c == '/' || c == '.' || c == ':' || c == '_'
			)
		{
			result += c;
		}
		else
		{
			int j = (short int)c;
			if (j < 0)
			{
				j += 256;
			}
			int i1, i0;
			i1 = j / 16;
			i0 = j - i1 * 16;
			result += '%';
			result += dec2hexChar(i1);
			result += dec2hexChar(i0);
		}
	}
	return result;
}

dec2hexChar()函数如下:

char dec2hexChar(short int n)
{
	if (0 <= n && n <= 9)
	{
		return char(short('0') + n);
	}
	else if (10 <= n && n <= 15)
	{
		return char(short('A') + n - 10);
	}
	else
	{
		return char(0);
	}
}


更多为你推荐