How do I create a URL shortener?

后端 未结 30 2494
我寻月下人不归
我寻月下人不归 2020-11-22 05:11

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to \"http://www.example.org/abcdef\

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:23

    C# version:

    public class UrlShortener 
    {
        private static String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private static int    BASE     = 62;
    
        public static String encode(int num)
        {
            StringBuilder sb = new StringBuilder();
    
            while ( num > 0 )
            {
                sb.Append( ALPHABET[( num % BASE )] );
                num /= BASE;
            }
    
            StringBuilder builder = new StringBuilder();
            for (int i = sb.Length - 1; i >= 0; i--)
            {
                builder.Append(sb[i]);
            }
            return builder.ToString(); 
        }
    
        public static int decode(String str)
        {
            int num = 0;
    
            for ( int i = 0, len = str.Length; i < len; i++ )
            {
                num = num * BASE + ALPHABET.IndexOf( str[(i)] ); 
            }
    
            return num;
        }   
    }
    

提交回复
热议问题