Search code examples
javadecimalhexurl-encodinghtml-encode

Convert All Chars in String to Different Escaped Formats(Java)


I'm looking to convert characters in a string to different escaped formats like the following, where the letter 'a' is the string being converted:

hex-url: %61
hex-html: a
decimal-html: &#97

I've searched used various built-in methods, but they merely take out the url-encoding specified chars(like '<') and escape them. I want to escape the ENTIRE string. Is there any way to convert a string into the formats above in java(using built in libraries, preferrably)?


Solution

  • public class StringEncoders
    {
        static public void main(String[] args)
        {
            System.out.println("hex-url: " + hexUrlEncode("a"));
            System.out.println("hex-html: " + hexHtmlEncode("a"));
            System.out.println("decimal-html: " + decimalHtmlEncode("a"));
        }
        static public String hexUrlEncode(String str)   {
            return encode(str, hexUrlEncoder);
        }
        static public String hexHtmlEncode(String str)  {
            return encode(str, hexHtmlEncoder);
        }
        static public String decimalHtmlEncode(String str)  {
            return encode(str, decimalHtmlEncoder);
        }
        static private String encode(String str, CharEncoder encoder)
        {
            StringBuilder buff = new StringBuilder();
            for ( int i = 0; i < str.length(); i++)
                encoder.encode(str.charAt(i), buff);
            return ""+buff;
        }
        private static class CharEncoder
        {
            String prefix, suffix;
            int radix;
            public CharEncoder(String prefix, String suffix, int radix)        {
                this.prefix = prefix;
                this.suffix = suffix;
                this.radix = radix;
            }
            void encode(char c, StringBuilder buff)     {
                buff.append(prefix).append(Integer.toString(c, radix)).append(suffix);
            }
        }
        static final CharEncoder hexUrlEncoder = new CharEncoder("%","",16);
        static final CharEncoder hexHtmlEncoder = new CharEncoder("&#x",";",16);
        static final CharEncoder decimalHtmlEncoder = new CharEncoder("&#",";",10); 
    }