C++中沒有內置的urlencode函數,但是可以通過自己實現一個來處理URL編碼。在自己實現的函數中,可以處理空格并將其轉換為"%20"或者"+"符號來表示空格。以下是一個簡單的示例代碼:
#include <iostream>
#include <sstream>
std::string urlencode(const std::string &str) {
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (std::string::const_iterator i = str.begin(), n = str.end(); i != n; ++i) {
std::string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char) c);
escaped << std::nouppercase;
}
return escaped.str();
}
int main() {
std::string input = "Hello World";
std::string output = urlencode(input);
std::cout << "Input: " << input << std::endl;
std::cout << "URL-encoded: " << output << std::endl;
return 0;
}
這個代碼片段中的urlencode
函數會將輸入字符串中的空格轉換為"%20"符號。您可以根據需要修改函數中的邏輯來適應不同的URL編碼需求。