什么是Java相当于javascript的String.fromCharCode?

时间:2010-05-31 21:36:51

标签: java javascript

它与javascript的java相当:

String.fromCharCode(n1, n2, ..., nX)

http://www.w3schools.com/jsref/jsref_fromCharCode.asp

1 个答案:

答案 0 :(得分:19)

这将是如下所示:

public static String fromCharCode(int... codePoints) {
    StringBuilder builder = new StringBuilder(codePoints.length);
    for (int codePoint : codePoints) {
        builder.append(Character.toChars(codePoint));
    }
    return builder.toString();
}

请注意,无法保证转换为char,因为代码点值可能超过char(65535)的上限。 char是在黑暗的Java时代建立的,Unicode 3.1尚未出现,超过65535个字符。

更新String实际上a constructor taking an int[](自Java 1.5引入以来,从头顶不知道它),它正确地处理了这个问题。以上内容可以简化如下:

public static String fromCharCode(int... codePoints) {
    return new String(codePoints, 0, codePoints.length);
}