Re: how to: int[] toInts(char[] chars)
Thomas Fritsch wrote:
Bo Vance schrieb:
How do achieve the method:
[snip]
See the API doc at
The methods
Character.codePointCount(char[],int,int)
and
Character.codePointAt(char[],int)
are all you need.
Thank you Thomas. I'll post what I have.
I will appreciate any comments.
import java.util.ArrayList;
import java.util.List;
public class Scratch {
/**
* Given an array of UTF16 encoded char,
* return an equivalent array of int codepoints.
*
* @param chars UTF16 encoded char[]
* @return int[] codepoints
* @throws Error on invalid UTF16 input
*/
int[] toInts(char[] chars) throws Error {
int[] ret = null;
if ((chars.length > 0)) {
List<Integer> buf
= new ArrayList<Integer>();
int idx = 0;
while (idx < chars.length) {
int codePoint
= Character.codePointAt(chars, idx, chars.length);
if ( codePoint < 0xD800 || codePoint > 0xDFFF )
{
buf.add(Integer.valueOf(codePoint));
idx += Character.charCount(codePoint);
}
else {
throw new Error
("index: " + (idx + 1));
}
}
ret = new int[buf.size()];
for (int i = 0; i < buf.size(); ++i) {
ret[i] = buf.get(i).intValue();
}
}
return ret == null ? null : ret;
}
public static void main(String[] args) {
char[] fourdish
= Character.toChars(Integer.parseInt("12409", 16));
char[][] test =
{
{ 'S', fourdish[0], fourdish[1] },
{ 'S', '\uDEEE' }
};
Scratch scr = new Scratch();
int count = 1;
try {
for (char[] ca : test) {
int[] temp = scr.toInts(ca);
for (int i : temp) {
System.out.print(i + " ");
}
System.out.println();
++count;
}
} catch (Error e) {
System.err.println
("Error test: " + count + ", " + e.getMessage());
}
}
}