Home >Backend Development >C++ >How Can I Efficiently Encode and Decode URLs in C ?
Devising an Effective URL Encoding/Decoding Solution in C
The task of encoding and decoding URLs to ensure seamless data transfer is often encountered in web development. In C , achieving this functionality requires a robust solution.
A Comprehensive Encoding Function
One approach to URL encoding in C is exemplified by the following code snippet:
#include <cctype> #include <iomanip> #include <sstream> #include <string> using namespace std; string url_encode(const string &value) { ostringstream escaped; escaped.fill('0'); escaped << hex; for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) { string::value_type c = (*i); // Preserve alphanumeric and designated characters if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { escaped << c; continue; } // Percent-encode non-compliant characters escaped << uppercase; escaped << '%' << setw(2) << int((unsigned char) c); escaped << nouppercase; } return escaped.str(); }
This function meticulously encodes non-compliant characters in accordance with the URL encoding standard, rendering it suitable for transmitting data across web platforms.
Decoding: An Exercise for the Reader
While not explicitly provided in the code, the decoding operation can be implemented as an exercise, providing ample opportunity to grasp the intricate details of URL handling.
The above is the detailed content of How Can I Efficiently Encode and Decode URLs in C ?. For more information, please follow other related articles on the PHP Chinese website!