如果我用Java 8的String.codePoints得到一个int codePoints的数组,数组的长度是否就是字符数?

If I use Java 8's String.codePoints to get an array of int codePoints, is it true that the length of the array is the count of characters?

给定 Java 中的 String stringstring.codePoints().toArray().length 是否根据人类认为有意义的实际字符反映了 String 的长度?换句话说,它是否平滑了转义字符和其他编码伪像?

Edit By "human" 我的意思是 "programmer" 因为我想大多数程序员会把 \r\n 看作两个字符,ESC 作为一个字符,等等。但是现在我看到连重音符号都被雾化了,所以没关系。

没有。

例如:


现在有争议的是其中一些是否可能 "actual characters that a human would find meaningful" ...但总体答案仍然是否。


您澄清如下:

By "human" I kind of meant "programmer" as I would imagine most programmers would see \r\n as two characters ...

比这更复杂。我是一名程序员,对我来说 \r\n 是否有意义取决于上下文。如果我正在阅读 README 文件,我的大脑会将白色 space 的差异视为没有语义重要性。但是如果我正在编写一个解析器,我的代码会考虑 whitespace ......这取决于它打算解析的语言。

String object.codePoints() returns Java 8.On 中的一个字符流,您正在调用 toArray 方法,因此它将以单独的方式处理每个字符并将 return 个字符。

只需检查 CharSequence 的 Javadoc 中的 codePoints() 方法即可:

Returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream. https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#codePoints--

和字符串类中的一个与代码点相关,以了解什么是代码点:

String(int[] codePoints, int offset, int count) Allocates a new String that contains characters from a subarray of the Unicode code point array argument.https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

代码点是表示 Unicode 代码点 (https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#unicode) 的整数,因此包括所有字符,即使是那些非人类可读的字符。