Introduction
URL encoding is a way of representing certain characters in a URL by replacing them with a %
symbol followed by their hexadecimal value. For example, the space character is encoded as %20
and the ampersand character is encoded as %26
. In some cases, you may need to decode a URL encoded string back to its original form in your C++ program. In this tutorial, we will guide you through the process of URL decoding a string in C++. Let’s get started!
Step 1: Include necessary libraries
To perform URL decoding in C++, we need to include the <string>
and <sstream>
libraries. The <string>
library provides functions for manipulating strings, while the <sstream>
library allows us to perform stream operations on strings.
#include <string>
#include <sstream>
Step 2: Create a function to decode a URL encoded string
Next, let’s define a function called urlDecode
that takes a URL encoded string as input and returns the decoded string.
std::string urlDecode(const std::string& urlEncodedString) {
std::istringstream input(urlEncodedString);
std::ostringstream output;
char hex;
int value;
while (input >> std::noskipws >> hex) {
if (hex == '%') {
if (input >> std::hex >> value) {
output << static_cast<char>(value);
}
}
else {
output << hex;
}
}
return output.str();
}
In this function, we use std::istringstream
to read characters from the URL encoded string. If a character is equal to ‘%’, it means that we have encountered an encoded character. We then read the hexadecimal value after ‘%’, convert it to an integer using std::hex
, and append the corresponding character to the std::ostringstream
called output
. If the character is not ‘%’, we simply append it to the output
.
Step 3: Decode a URL encoded string
Now that we have our urlDecode
function, let’s see how we can use it to decode a URL encoded string.
int main() {
std::string urlEncodedString = ""Hello%20World%21"";
std::string decodedString = urlDecode(urlEncodedString);
std::cout << ""Decoded string: "" << decodedString << std::endl;
return 0;
}
In this example, we have a URL encoded string ““Hello%20World%21"” which represents ““Hello World!””. We pass this string to the urlDecode
function, and the decoded string ““Hello World!”” is stored in the variable decodedString
. Finally, we print the decoded string to the console using std::cout
.
Step 4: Compile and run the program
To compile and run the program, save the code in a .cpp
file (e.g., url_decode.cpp
). Then, open a terminal or command prompt and navigate to the directory where the file is saved. Use a C++ compiler, such as g++, to compile the program.
g++ url_decode.cpp -o url_decode
After successful compilation, run the executable file.
./url_decode
You should see the following output:
Decoded string: Hello World!
Congratulations! You have successfully decoded a URL encoded string in C++. Feel free to use the urlDecode
function in your projects to decode any URL encoded strings as needed.
I hope you found this tutorial helpful!