如何将代表代码点的字符串转换为适当的字符?
例如,我想要一个获取U+00E4并返回的函数ä.
我知道在字符类中我有一个函数toChars(int codePoint),它接受一个整数,但是没有函数接受这种类型的字符串.
有内置函数还是我必须对字符串进行一些转换才能获得可以发送给函数的整数?
Ani*_*dha 27
代码点写为十六进制数字,前缀为 U+
所以,你可以做到这一点
int codepoint=Integer.parseInt(yourString.substring(2),16);
char[] ch=Character.toChars(codepoint);
Run Code Online (Sandbox Code Playgroud)
从 Kotlin 转换而来:
public String codepointToString(int cp) {
StringBuilder sb = new StringBuilder();
if (Character.isBmpCodePoint(cp)) {
sb.append((char) cp);
} else if (Character.isValidCodePoint(cp)) {
sb.append(Character.highSurrogate(cp));
sb.append(Character.lowSurrogate(cp));
} else {
sb.append('?');
}
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
该问题要求一个函数来转换表示 Unicode 代码点的字符串值(即,"+Unnnn"而不是 Java 格式的"\unnnn"或"0xnnnn)。但是,较新版本的 Java 具有增强功能,可以简化包含 Unicode 格式的多个代码点的字符串的处理:
public static String toString?(int codePoint)将其添加到CharacterJava中11.类返回String,而不是一个char[],这样Character.toString(0x00E4)的回报"ä"。这些增强功能允许采用不同的方法来解决 OP 中提出的问题。此方法将 Unicode 格式的一组代码点转换为String单个语句中的可读代码:
void processUnicode() {
// Create a test string containing "Hello World " with code points in Unicode format.
// Include an invalid code point (+U0wxyz), and a code point outside the Unicode range (+U70FFFF).
String data = "+U0048+U0065+U006c+U006c+U0wxyz+U006f+U0020+U0057+U70FFFF+U006f+U0072+U006c+U0000064+U20+U1f601";
String text = Arrays.stream(data.split("\\+U"))
.filter(s -> ! s.isEmpty()) // First element returned by split() is a zero length string.
.map(s -> {
try {
return Integer.parseInt(s, 16);
} catch (NumberFormatException e) {
System.out.println("Ignoring element [" + s + "]: NumberFormatException from parseInt(\"" + s + "\"}");
}
return null; // If the code point is not represented as a valid hex String.
})
.filter(v -> v != null) // Ignore syntactically invalid code points.
.filter(i -> Character.isValidCodePoint(i)) // Ignore code points outside of Unicode range.
.map(i -> Character.toString(i)) // Obtain the string value directly from the code point. (Requires JDK >= 11 )
.collect(Collectors.joining());
System.out.println(text); // Prints "Hello World "
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
run:
Ignoring element [0wxyz]: NumberFormatException from parseInt("0wxyz"}
Hello World
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)
笔记:
Stream处理中的多个中间操作分散的。当然,同样的代码仍可用于处理 Unicode 格式的单个代码点。Stream,例如大小写转换、删除表情符号等。