如何将字符串中的特殊字符转换为unicode?

How to convert special characters in a string to unicode?

我找不到这个问题的答案,在这里尝试了几个答案以找到有效的方法,但无济于事。 我正在处理的应用程序使用用户名来创建其中包含该名称的 PDF。然而,当某人的名字包含像 "Yağmur" 这样的特殊字符时,pdf 的创建者会吓坏并忽略这个特殊字符。 但是,当它获得等效的 unicode ("Yağmur") 时,它会在 pdf 中打印 "Yağmur"

我如何检查 name/string 是否有任何特殊字符 (regex = "[^a-z0-9 ]") 并在找到时用它的 unicode 等效字符替换该字符并返回新的 unicode 字符串?

我将尝试以通用方式提供解决方案,因为您正在使用的框架并未作为问题陈述的一部分提及。

很久以前我也遇到过同样的问题。如果您将 text/char 编码设置为 UTF-8,这应该由 pdf 引擎处理。请找到如何在您的 pdf 生成框架中设置编码并尝试一下。希望对您有所帮助!!

一种骇人听闻的方法如下:

/*
 * 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&#287;mur.

当然,您可以使用 "conversion" 逻辑并决定转换哪些范围。