Create a URL shortener in C++

In this tutorial, we will learn how to shorten a URL in C++.

URL shortening is used to create a unique shorter alternative for long URLs. These save a lot of space while storing, displaying on a website, or messaging. Once clicked on a short URL, it converts ID to URL and redirects to the original URL’s website. We convert each alphabet in URL to int and add it to the final URL ID. We have 62 possible chars i.e. A-Z, a-z, 0-9, if we can make a URL of length n, then we can have a total of 62^n URLs.

Example: If a company wants to serve more than 1 billion URLs, we use this technique to reduce the size of the URL and keep it as short as possible.

URL shorter program in C++

#include <bits/stdc++.h>
using namespace std;

string convIDtoURL(int n) {
  
    // Char array having all chars (A to Z), (a to z) and (0 to 9)
    char alphaMap[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"
        "ghijklmnopqrstuvwxyz0123456789";

  string url;

  while (n > 0) { 
    // converting urlID to url
    url.push_back(alphaMap[n%62]);
    n /= 62;
  }

  reverse(url.begin(), url.end());

  return url;
}

int convURLtoID(string shortURL) {
  int urlID = 0; 

  for (int i=0; i < shortURL.length(); i++) {
     // if char is in between A and Z
     if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
        urlID = urlID*62 + shortURL[i] - 'A';

     // if char is in between a and z (till 26 we have A to Z)
     if ('a' <= shortURL[i] && shortURL[i] <= 'z')
        urlID = urlID*62 + shortURL[i] - 'a' + 26;
    
     // if char is in between 0 and 9 (till 52 we have a to b)
     if ('0' <= shortURL[i] && shortURL[i] <= '9')
        urlID = urlID*62 + shortURL[i] - '0' + 52;
  }

  return urlID;
}

int main() {

    int n = 12345;
    string url = convIDtoURL(n);
    cout << "Generated short url is www.urlShortner.com/" << url << endl;
    cout << "ID from URL is " << convURLtoID(url);
  
    return 0;
}

Output

Generated short url is www.urlShortner.com/DNH
ID from URL is 12345

Also read: Detect URL in a string in C++

Leave a Reply

Your email address will not be published.