c++ HTML URL 编码表转化
时间: 2023-11-18 12:17:31 浏览: 166
以下是使用 C++ 实现将字符串中的特殊字符转换为 HTML URL 编码的示例代码:
```c++
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
string urlEncode(const string& str) {
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator it = str.begin(), end = str.end(); it != end; ++it) {
string::value_type c = (*it);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
}
// Any other characters are percent-encoded
else {
escaped << uppercase;
escaped << '%' << setw(2) << int((unsigned char)(c));
escaped << nouppercase;
}
}
return escaped.str();
}
int main() {
string str = "HTML URL 编码表";
string encodedStr = urlEncode(str);
cout << "转换前:" << str << endl;
cout << "转换后:" << encodedStr << endl;
return 0;
}
```
输出结果:
```
转换前:HTML URL 编码表
转换后:HTML%20URL%20%E7%BC%96%E7%A0%81%E8%A1%A8
```
可以看到,特殊字符被转换为了 HTML URL 编码形式。
阅读全文