2015-06-19 96 views
6

假設我有一個字符串富= 「這是一個蘋果」字符串轉換爲它的Unicode代碼點

的統一代碼點當量將是

\\x74\\x68\\x69\\x73.......... \\x61\\x70\\x70\\x6c\\x65

T h i s ............. a p p l e 

如何從字符串foo轉換

字符串 「\\x74\\x68\\x69\\x73.......... \\x61\\x70\\x70\\x6c\\x65

+0

這是一種通過每個個性做...可以引導你在正確的方向:HTTP://www.java2s。 COM /教程/的Java/0120__Development/Convertsthestringtot heunicodeformat.htm – CubeJockey

+0

轉換的字符串的第一部分不應該是\\ x54嗎? – JamesB

+0

這可能有所幫助:http://www.java2s.com/Code/Java/I18N/ConvertintoHexadecimalnotationofUnicode.htm – JamesB

回答

1

試試這個..

 public static String generateUnicode(String input) { 
      StringBuilder b = new StringBuilder(input.length()); 
      for (char c : input.toCharArray()) { 

       b.append(String.format("\\u%04x", (int) c)); 

      } 
      return b.toString(); 
     } 
+0

char不是codepoint(雖然大部分時候是這樣) – njzk2

+0

沒有'UTF-16'這樣的東西,碼點。 Unicode代碼點是個別的字符值。 「UTF-16」是使用至少2個字節的代碼點的編碼。低平面中的代碼點使用其精確值進行編碼。 (因此2之間的共同混淆)。補充飛機使用代理對,這使事情更復雜一點 – njzk2

+1

這將在大多數情況下工作。它不起作用的情況是,如果有代理對使用(僅限非常罕見的字符),因爲在BMP(基本多語種計劃)中,由utf-16定義的編碼僅僅是使用2個字節的簡單代碼點。 – njzk2

0

這裏工作的代碼片段進行轉換:

public class HexTest { 

    public static void main(String[] args) { 

     String testStr = "hello日本語 "; 

     System.out.println(stringToUnicode3Representation(testStr)); 
    } 

    private static String stringToUnicode3Representation(String str) { 
     StringBuilder result = new StringBuilder(); 
     char[] charArr = str.toCharArray(); 
     for (int i = 0; i < charArr.length; i++) { 
      result.append("\\u").append(Integer.toHexString(charArr[i] | 0x10000).substring(1)); 
     } 
     return result.toString(); 
    } 
} 

這顯示:

\ u0068 \ u0065 \ u006c \ u006c \ u006f \ u65e5 \ u672c \ u8a9e \ü 0020

如果您想擺脫多餘的零,請按照here中所述詳細說明它。

這裏另一個版本來進行轉換,通過傳遞"This is an apple"

\ U54 \ U68 \ U69 \ U73 \ U20 \ U69 \ U73 \ U20 \ U61 \ U6E \ U20 \ U61 \ U70 \ U70 \ U6C \ U65

使用:

private static String str2UnicodeRepresentation(String str) { 
    StringBuilder result = new StringBuilder(); 
    for (int i = 0; i < str.length(); i++) { 
     int cp = Character.codePointAt(str, i); 
     int charCount = Character.charCount(cp); 
     //UTF characters may use more than 1 char to be represented 
     if (charCount == 2) { 
      i++; 
     } 
     result.append(String.format("\\u%x", cp)); 
    } 
    return result.toString(); 
}