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

How to Robustly Encode and Decode URLs in C ?

DDD
Release: 2024-12-04 08:48:12
Original
721 people have browsed it

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

#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();

}

Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template