THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Exercise 13.5: Write a method to convert strings containing decimal numbers into comma-punctuated
numbers, with a comma every third digit from the right. For example, given the string "1543729", the
method should return the string "1,543,729".


Exercise 13.6: Modify the method to accept parameters specifying the separator character to use and the
number of digits between separator characters.


13.5. Working with UTF-16


In "Working with UTF-16" on page 196, we described a number of utility methods provided by the
Character class to ease working with the supplementary Unicode characters (those greater in value than
0xFFFF that require encoding as a pair of char values in a CharSequence). Each of the String,
StringBuilder, and StringBuffer classes provides these methods:


public intcodePointAt(int index)

Returns the code point defined at the given index in this, taking into
account that it may be a supplementary character represented by the pair
this.charAt(index) and this.charAt(index+1).

public intcodePointBefore(int index)

Returns the code point defined at the given index in this, taking into
account that it may be a supplementary character represented by the pair
this.charAt(index-2) and this.charAt(index-1).

public intcodePointCount(int start, int end)

Returns the number of code points defined in this.charAt(start) to
this.charAt(end), taking into account surrogate pairs. Any unpaired
surrogate values count as one code point each.

public intoffsetByCodePoints(int index, int
numberOfCodePoints)

Returns the index into this that is numberOfCodePoints away from
index, taking into account surrogate pairs.

In addition, the StringBuilder and StringBuffer classes define the appendCodePoint method
that takes an int representing an arbitrary Unicode character, encodes it as a surrogate pair if needed, and
appends it to the end of the buffer. Curiously, there is no corresponding insertCodePoint method.


Finally, the String class also provides the following constructor:


publicString(int[] codePoints, int start, int count)

Constructs a new String with the contents from codePoints[start]
up to a maximum of count code points, with supplementary characters
encoded as surrogate pairs as needed. If any value in the array is not a valid
Unicode code point, then IllegalArgumentException is thrown.

When ideas fail, words come in very handy.
Free download pdf