Advertisement
Willcode4cash

URL Shortening Implementation

Aug 17th, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. public class UrlShortener
  2. {
  3.     public static readonly string Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
  4.     public static readonly int Base = Alphabet.Length;
  5.  
  6.     public static string Encode(int i)
  7.     {
  8.         if (i == 0) return Alphabet[0].ToString();
  9.         var s = string.Empty;
  10.         while (i > 0)
  11.         {  
  12.             s += Alphabet[i % Base];
  13.             i = i / Base;
  14.         }
  15.         return string.Join(string.Empty, s.Reverse());
  16.     }
  17.  
  18.     public static int Decode(string s)
  19.     {
  20.         var i = 0;
  21.         foreach (var c in s)
  22.         {
  23.             i = (i * Base) + Alphabet.IndexOf(c);
  24.         }
  25.         return i;
  26.     }
  27. }
  28.  
  29. public class Program
  30. {
  31.     public static void main()
  32.     {
  33.         // Insert URL to be shortened into database and get it's record ID
  34.         //  e.g. "http://www.foo.bar" => 155885
  35.         // Encode 155885 which results in the string "dmkf"
  36.         // This is the parameter to your Url shortener
  37.         //  e.g. "http://www.url.me/dmkf"
  38.         // Decode the parameter to get the original record ID
  39.         // Redirect the user to the URL represented by the record ID
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement