3 ms·
> The leftpad function provided[1] didn’t take a string, but a char[]. Thankfully, it’s easy to convert from String objects, using the .toCharArray() function.
by marginalia_nu 1y ago
> The leftpad function provided[1] didn’t take a string, but a char[]. Thankfully, it’s easy to convert from String objects, using the .toCharArray() function. So I did that.
Java's unicode handling is a monumental footgun of the most devastating variety where it works for most common cases, and almost all code that is not written with care to how it is handled will not deal well with code points that require more than 2 bytes to represent.
If you insist on using a char array (which is a bit unidiomatic), you should be using Character$charPointCount[2] to figure out how many code points are in the array, and even then you're probably SOL with regards to non-trivial emojis. String$charPointCount[3] is also an option if you want to use String and StringBuilder to do the padding, which arguably be more idiomatic.
[1] https://github.com/hwayne/lets-prove-leftpad/blob/ea9c0f09a2d3e981d82118497c307844fc7b1f49/java/LeftPad.java#L7 https://github.com/hwayne/lets-prove-leftpad/blob/ea9c0f09a2...
[2] https://docs.oracle.com/en/java/javase/25/docs/api//java.base/java/lang/Character.html#codePointCount(char%5B%5D,int,int) https://docs.oracle.com/en/java/javase/25/docs/api//java.bas...
[3] https://docs.oracle.com/en/java/javase/25/docs/api//java.base/java/lang/String.html#codePointCount(int,int) https://docs.oracle.com/en/java/javase/25/docs/api//java.bas...