Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  17] [ 1]  / answers: 1 / hits: 17133  / 14 Years ago, mon, may 31, 2010, 12:00:00

What it the java equivalent of javascript's:



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


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


More From » java

 Answers
12

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);
}

[#96631] Thursday, May 27, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mariann

Total Points: 201
Total Questions: 133
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;