Home >Backend Development >C++ >How to Robustly Encode and Decode URLs in C ?

How to Robustly Encode and Decode URLs in C ?

DDD
DDDOriginal
2024-12-04 08:48:12682browse

How to Robustly Encode and Decode URLs in C  ?

Encoding and Decoding URLs in C

Question:

Encode and decode URLs in C . Is there any robust code available?

Answer:

Encoding:

To resolve a URL encoding issue, a custom C function was developed based on a C sample code:

#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 valid symbols
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
            continue;
        }

        // Percent-encode other characters
        escaped << uppercase;
        escaped << '%' << setw(2) << int((unsigned char) c);
        escaped << nouppercase;
    }

    return escaped.str();
}

Decoding:

Implementing a decoding function is an optional exercise.

The above is the detailed content of How to Robustly Encode and Decode URLs in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn