2
votes

Trying to solve an issue with trimming a string.

Are there any ascii chars that are not counted in either length() or substring(int, int)?

Ex. if the string is coming from a serialized object outside your program and contains characters such as "start of text" (ascii hx2) or "bell" (ascii hx7) will those characters be considered in either length() or substring(int, int)?

2
Java strings are not ASCII, they are UTF-16. - Solomon Slow

2 Answers

3
votes

See the documentation for String#length:

Returns the length of this string. The length is equal to the number of Unicode code units in the string.

This means that all characters are included in the length. Specifically, this will return the number of chars required to represent the string in Java.

However, of note is that certain Unicode character will actually take up two chars in the string due to the way Java handles Unicode characters using UTF-16. See the relevant documentation for more information.

1
votes

Are there any ascii chars that are not counted in either length() or substring(int, int)?

No, there aren't any. Both of these methods are "dumb" and will return the number of chars stored in the underlying character array of the String object (and in fact, .length() is inherited from CharSequence).

Whether they be ASCII control characters, "non characters" such as U+0000 and U+FFFF, all will be counted.