Home >Backend Development >C++ >How to Encode and Decode URLs in C ?
Encoding and Decoding URLs in C
Many applications handle data that needs to be transmitted across the network via URLs. In these scenarios, it is crucial to encode the URL to ensure that special characters and spaces are represented correctly.
Encoding a URL
Here's a C function that encodes a URL:
#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); // Keep alphanumeric and other accepted characters intact if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { escaped << c; continue; } // Any other characters are percent-encoded escaped << uppercase; escaped << '%' << setw(2) << int((unsigned char) c); escaped << nouppercase; } return escaped.str(); }
Decoding a URL (Exercise)
As mentioned in the answer to the original question, implementing URL decoding is left as an exercise for you. This function would take an escaped URL and convert it back to its original format.
Example Usage
To encode a URL, simply call the url_encode function passing in the input string.
To decode a URL, implement the decoding function and call it with the escaped string as the input.
The above is the detailed content of How to Encode and Decode URLs in C ?. For more information, please follow other related articles on the PHP Chinese website!