My Blog

My WordPress Blog

My Blog

My WordPress Blog

Simple URL Shortener in C++

cppCopy code#include <iostream>
#include <unordered_map>
#include <string>
#include <ctime>

class URLShortener {
private:
std::unordered_map&lt;std::string, std::string&gt; url_map; // Maps short URL to original URL
std::unordered_map&lt;std::string, std::string&gt; reverse_map; // Maps original URL to short URL
const std::string base_url = "http://short.url/";

std::string generateShortURL() {
    static const char alphanum&#91;] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    std::string short_url;
    
    for (int i = 0; i &lt; 6; ++i) {
        short_url += alphanum&#91;rand() % (sizeof(alphanum) - 1)];
    }
    
    return short_url;
}
public:
URLShortener() {
    std::srand(static_cast&lt;unsigned&gt;(std::time(nullptr))); // Seed for randomness
}
std::string shortenURL(const std::string&amp; original_url) {
    if (reverse_map.find(original_url) != reverse_map.end()) {
        return base_url + reverse_map&#91;original_url]; // Return existing short URL
    }
    
    std::string short_url = generateShortURL();
    while (url_map.find(short_url) != url_map.end()) {
        short_url = generateShortURL(); // Ensure unique short URL
    }
    
    url_map&#91;short_url] = original_url;
    reverse_map&#91;original_url] = short_url;
    return base_url + short_url;
}
std::string getOriginalURL(const std::string&amp; short_url) {
    std::string short_code = short_url.substr(base_url.length());
    if (url_map.find(short_code) != url_map.end()) {
        return url_map&#91;short_code];
    }
    return "URL not found!";
}
}; int main() {
URLShortener url_shortener;
std::string original_url;
std::cout &lt;&lt; "Enter a URL to shorten: ";
std::cin &gt;&gt; original_url;
std::string short_url = url_shortener.shortenURL(original_url);
std::cout &lt;&lt; "Shortened URL: " &lt;&lt; short_url &lt;&lt; std::endl;
std::cout &lt;&lt; "Enter the short URL to retrieve the original: ";
std::string input_short_url;
std::cin &gt;&gt; input_short_url;
std::string retrieved_url = url_shortener.getOriginalURL(input_short_url);
std::cout &lt;&lt; "Original URL: " &lt;&lt; retrieved_url &lt;&lt; std::endl;
return 0;
}

How It Works

  1. URL Mapping: It uses two hash maps to store mappings between short URLs and original URLs.
  2. Short URL Generation: A random string of characters is generated for the short URL.
  3. Collision Handling: The program checks for existing short URLs to ensure uniqueness.
  4. User Input: The user can input a URL to shorten and retrieve the original URL using the shortened link.
Simple URL Shortener in C++

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top