对于相同的字符串,SQLite 的长度是否会 return 与 Java 的长度方法不同?

For a same String, will SQLite's length will ever return a different value than Java's length method?

给一个相同的字符串数据

  1. SQLite 对其 TEXT 列执行 length 计算。
  2. TEXT列被读入(使用Android房间数据库)Java字符串,然后Java执行String.length()

这些是否有可能产生 2 个不同的值?

我用英文和非英文字符做了一个粗略的测试。两者产生相同的值。

但是,我不确定是否遗漏了任何边缘情况?

因为您正在寻找边缘情况...

来自 SQLite 的 Built-In Scalar SQL Functions:

length(X)
For a string value X,
the length(X) function returns the number of characters (not bytes) in X
prior to the first NUL character. (emphasis mine)
Since SQLite strings do not normally contain NUL characters,
the length(X) function will usually return the total number of characters in the string X....

所以,SQLite,用于:

SELECT LENGTH('a' || CHAR(0) || 'b')

将return1,

但 Java,因为:

String s = "a" + Character.toString('[=11=]') + "b";
System.out.println("" + s.length());

将 return 3.

根据Sqlite的documentationNUL字符(ASCII 0x00, Unicode \u0000)在TEXT字段可以导致不同length 值。

以文字为例Hello\u0000World

Sqlite 将 return 长度为 16

Java 将 return 长度为 11

Java 会将 NUL 字符计为 1,而 Sqlite 将计为 6。相同的文本将具有不同的值。

在某些情况下,长度可能会有所不同,Java 使用 UTF-16 进行内部字符串表示,因此某些类型的字符需要代理项对才能存储在内存中。 Java 的 String.length() 没有考虑到这一点。

使用表情符号字符的简单示例

    class HelloWorld {
    public static void main(String[] args) {
        System.out.println("".length());
    }}

这将打印 2。

另一方面,sqlite 的文档状态:

For a string value X, the length(X) function returns the number of characters (not bytes) in X prior to the first NUL character.

指定统计个字符

sqlite> select length(''); 

这将 return 1.

这不是“表情符号”独有的,对于某些具有“高”代码点的字符(如某些亚洲字符)的语言也是如此

已使用 sqlite 3.28.0 和 openjdk 版本“1.8.0_252”进行测试。我认为它应该适用于您的堆栈。