Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the java equivalent to javascript's String.fromCharCode?

What it the java equivalent of javascript's:

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

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

like image 243
jon077 Avatar asked May 31 '10 21:05

jon077


1 Answers

That would be something like as follows:

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

Note that casting to char isn't guaranteed to work because the codepoint value might exceed the upper limit of char (65535). The char was established in the dark Java ages when Unicode 3.1 wasn't out yet which goes beyond 65535 characters.

Update: the String has actually a constructor taking an int[] (introduced since Java 1.5, didn't knew it from top of head), which handles this issue correctly. The above could be simplified as follows:

public static String fromCharCode(int... codePoints) {
    return new String(codePoints, 0, codePoints.length);
}
like image 55
BalusC Avatar answered Sep 20 '22 01:09

BalusC