Convert String to UTF-8 literal - Java java.lang

Java examples for java.lang:String UTF

Description

Convert String to UTF-8 literal

Demo Code

/*/*  w  w w.ja  v  a2s  .  c  o  m*/
 * MoXie (SysTem128@GMail.Com) 2009-3-11 10:06:36
 * 
 * Copyright © 2008-2009 Zoeey.Org
 * Code license: GNU Lesser General Public License Version 3
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 */
//package com.java2s;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(utf8_literal(str));
    }

    private static final char[] hexs = "0123456789abcdef".toCharArray();

    public static String utf8_literal(String str) {
        StringBuilder strBuilder = new StringBuilder(str.length());
        CharacterIterator it = new StringCharacterIterator(str);
        for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it
                .next()) {
            switch (ch) {
            case '"':
                strBuilder.append("\\\"");
                break;
            case '\\':
                strBuilder.append("\\\\");
                break;
            case '/':
                strBuilder.append("\\/");
                break;
            case '\b':
                strBuilder.append("\\b");
                break;
            case '\f':
                strBuilder.append("\\f");
                break;
            case '\n':
                strBuilder.append("\\n");
                break;
            case '\r':
                strBuilder.append("\\r");
                break;
            case '\t':
                strBuilder.append("\\t");
                break;
            default:
                if (ch < 26 || ch > 126) {
                    toUnicode(strBuilder, ch);
                } else {
                    strBuilder.append(ch);
                }
                break;
            }
        }
        return strBuilder.toString();
    }

    private static void toUnicode(StringBuilder strBuilder, char ch) {
        /**
         * standard unicode format
         */
        strBuilder.append("\\u");
        for (int i = 4; i > 0; i--) {
            strBuilder.append(hexs[(ch & 0xf000) >> 12]);
            ch <<= 4;
        }
    }
}

Related Tutorials