Why isn’t String‘s length() accurate?
Why isn’t String‘s length() accurate?
The accuracy of the String class's length() method in Java depends on what is meant by "accurate." The length() method accurately reports the number of 16-bit char values that make up the String object, which corresponds to the number of char units in the underlying char array. However, this count may not align with a human's intuitive understanding of the length of a string in terms of the number of visible characters or graphemes, especially when dealing with Unicode characters that require more than one char value.
Unicode characters can be represented by a single code unit (char), or they can be composed of a pair of code units known as a surrogate pair. This is because the char data type in Java uses UTF-16 encoding, where each char is 16 bits. The Unicode standard has more characters than can be represented in 16 bits, so characters outside the Basic Multilingual Plane (BMP) are represented using two 16-bit code units.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.