It looks right to me. If you want to iterate over code points in a string, you can wrap this code in Iterable :
public static Iterable<Integer> getCodePoints(final String text) { return new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int nextIndex = 0; @Override public boolean hasNext() { return nextIndex < text.length(); } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } int codePoint = text.codePointAt(nextIndex); nextIndex += Character.charCount(codePoint); return codePoint; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
Or you can change the method to just return int[] , of course:
public static int[] getCodePoints(String text) { int[] ret = new int[text.codePointCount(0, text.length())]; int charIndex = 0; for (int i = 0; i < ret.length; i++) { ret[i] = text.codePointAt(charIndex); charIndex += Character.charCount(ret[i]); } return ret; }
I agree that it is a pity that the Java libraries do not expose similar methods already, but at least they are not so difficult to write.
source share