Home > Backend Development > C++ > How Can I Efficiently Encode and Decode URLs in C ?

How Can I Efficiently Encode and Decode URLs in C ?

Linda Hamilton
Release: 2024-12-03 22:04:11
Original
420 people have browsed it

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template