Welcome to this guide and tutorial on URL encoding in C! In this post, we will explore how to encode a string in C to ensure its compatibility with URLs.

URLs contain special characters that cannot be directly used in the web. URL encoding is the process of converting these characters into a format that can be safely transmitted and interpreted by browsers and servers. For example, converting a space character to “"%20"” or a plus sign to “"%2B”".

To perform URL encoding in C, we can make use of the standard C library functions like sprintf() and isalnum(). Let’s see how it’s done step by step.

Step 1: Include the necessary headers

First, include the necessary headers in your C program to use the required functions:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

Step 2: Implement the URL encoding function

Next, implement a function that takes a string as input and URL encodes it. Here’s an example implementation:

char* urlEncode(const char* string) {
    const char* hexChars = ""0123456789ABCDEF"";
    size_t length = strlen(string);
    char* encodedString = malloc(3 * length + 1); // Allocate memory for the encoded string
    size_t index = 0;

    for (size_t i = 0; i < length; i++) {
        char currentChar = string[i];

        if (isalnum(currentChar) || currentChar == '-' || currentChar == '_' || currentChar == '.') {
            encodedString[index++] = currentChar; // Append alphanumeric and safe characters as is
        } else if (currentChar == ' ') {
            encodedString[index++] = '+'; // Convert space to '+'
        } else {
            encodedString[index++] = '%'; // Convert other characters to percent-encoding
            encodedString[index++] = hexChars[(currentChar >> 4) & 0xF]; // Append first hexadecimal digit
            encodedString[index++] = hexChars[currentChar & 0xF]; // Append second hexadecimal digit
        }
    }

    encodedString[index] = '\0'; // Add null terminator

    return encodedString;
}

Step 3: Test the URL encoding function

Finally, let’s test the URL encoding function with a sample string and print the encoded result:

int main() {
    const char* inputString = ""Hello, World! How are you?"";
    char* encodedString = urlEncode(inputString);

    printf(""Encoded string: %s\n"", encodedString);

    free(encodedString); // Remember to free the allocated memory

    return 0;
}

The output will be:

Encoded string: Hello%2C+World%21+How+are+you%3F

Conclusion

Congratulations! You have successfully learned how to URL encode a string in C. You can now use this knowledge to ensure the compatibility and safety of your URL parameters and other data transmitted through URLs.

I hope you found this tutorial helpful!