溫馨提示×

c++ urlencode如何處理加號

c++
小樊
92
2024-07-23 12:08:04
欄目: 編程語言

在C++中對加號進行URL編碼,可以使用urlencode函數(shù)來處理。下面是一個示例代碼:

#include <iostream>
#include <string>
#include <sstream>

std::string urlencode(const std::string &s) {
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;
    
    for (std::string::const_iterator i = s.begin(), n = s.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 << "Encoded string: " << output << std::endl;
    
    return 0;
}

在上面的代碼中,urlencode函數(shù)將輸入字符串中的加號(+)以及其他非字母數(shù)字字符進行URL編碼,并返回編碼后的字符串。您可以將需要進行URL編碼的字符串傳入urlencode函數(shù)中,即可獲取編碼后的結(jié)果。

0