Java UTF from toUtf8(String s)

Here you can find the source of toUtf8(String s)

Description

to Utf

License

Open Source License

Declaration

public static String toUtf8(String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {

    public static String toUtf8(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);/*from  www .j a v  a 2 s  . c om*/
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }

        return sb.toString();
    }
}

Related

  1. toUTF(String... str)
  2. toUTF8(byte[] outputBuffer, String string, char[] workingBuffer)
  3. toUtf8(final String string)
  4. toUtf8(String hex)
  5. toUTF8(String oldStr)
  6. toUTF8(String s)
  7. toUTF8(String s, String encoding)
  8. toUTF8(String str)
  9. toUTF8(String string)