[英]How to convert special characters in a string to unicode?
我找不到這個問題的答案,在這里嘗試了幾個答案,結合找到有用的東西,但無濟於事。 我正在處理的應用程序使用用戶名來創建具有該名稱的PDF。 但是,當某人的名字包含像"Yağmur"
這樣的特殊字符時,pdf創建者會"Yağmur"
並省略這個特殊字符。 然而,當它獲得unicode等價物( "Yağmur"
)時,它會在pdf中打印"Yağmur"
。
如何檢查任何特殊字符的名稱/字符串(regex = "[^a-z0-9 ]"
),找到后,用等效的unicode替換該字符並返回新的unicoded字符串?
我將嘗試以通用方式提供解決方案,因為您正在使用的框架工作未被提及作為問題陳述的一部分。
我很久以前也遇到過同樣的問題。 如果將text / char編碼設置為UTF-8,則應由pdf引擎處理。 請找到如何在框架中設置編碼以生成pdf並進行試用。 希望能幫助到你 !!
一種執行此操作的hackish方式如下:
/*
* TODO: poorly named
*/
public static String convertUnicodePoints(String input) {
// getting char array from input
char[] chars = input.toCharArray();
// initializing output
StringBuilder sb = new StringBuilder();
// iterating input chars
for (int i = 0; i < input.length(); i++) {
// checking character code point to infer whether "conversion" is required
// here, picking an arbitrary code point 125 as boundary
if (Character.codePointAt(input, i) < 125) {
sb.append(chars[i]);
}
// need to "convert", code point > boundary
else {
// for hex representation: prepends as many 0s as required
// to get a hex string of the char code point, 4 characters long
// sb.append(String.format("&#xu%04X;", (int)chars[i]));
// for decimal representation, which is what you want here
sb.append(String.format("&#%d;", (int)chars[i]));
}
}
return sb.toString();
}
如果執行: System.out.println(convertUnicodePoints("Yağmur"));
...
......你會得到的: Yağmur
。
當然,您可以使用“轉換”邏輯並決定轉換哪些范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.