Java Unicode to UTF unicodeToUTF(String in)

Here you can find the source of unicodeToUTF(String in)

Description

unicode To UTF

License

Open Source License

Declaration

public static String unicodeToUTF(String in) 

Method Source Code

//package com.java2s;
/*// www  . j  a  v a2s  .  c  o  m
 *   
 *
 * Copyright  1990-2006 Sun Microsystems, Inc. All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version
 * 2 only, as published by the Free Software Foundation. 
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 2 for more details (a copy is
 * included at /legal/license.txt). 
 * 
 * You should have received a copy of the GNU General Public License
 * version 2 along with this work; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA 
 * 
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 or visit www.sun.com if you need additional
 * information or have any questions. 
 */

public class Main {
    public static String unicodeToUTF(String in) {
        int n = in.length();
        StringBuffer t = new StringBuffer(3 * n); // conservative sizing.
        int nt = 0;
        for (int i = 0; i < n; i++) {
            char c = in.charAt(i);
            if (c == '\u0000') {
                t.append('\u00c0');
                t.append('\u0080');
                nt += 2;
            } else if (c <= '\u007f') {
                t.append(c);
                nt += 1;
            } else if (c <= '\u07ff') {
                t.append((char) ('\u00c0' | (c >> 6)));
                t.append((char) ('\u0080' | (c & 0x3f)));
                nt += 2;
            } else {
                t.append((char) ('\u00e0' | (c >> 12)));
                t.append((char) ('\u0080' | ((c >> 6) & 0x3f)));
                t.append((char) ('\u0080' | (c & 0x3f)));
                nt += 3;
            }
        }
        if (nt == n)
            return in;
        else
            return t.toString();
    }
}

Related

  1. unicodeToUtf8(String theString)