获取QString长度(以字符为单位,而不是字节)

时间:2012-12-22 01:04:32

标签: c++ qt qstring

我需要得到实际的字符数(不是字节数),类似于在V8中获取字符串长度时的输出。

这与Twitter一起使用是必要的,无论使用何种语言,它都按字符数计算,即使使用UTF-8(它也不按字节长度)。

前:

在chrome / chromium js控制台中,或在nodejs中:

> "Schöne Grüße".length
< 12

在Qt 4.8.2中,尝试QString someStr = "Schöne Grüße"; cout << someStr.length()将输出15,这不是我的目标。

2 个答案:

答案 0 :(得分:3)

如果您真的想要计算字形集群(即用户感知的字符)而不是代码单元,则需要QTextBoundaryFinder。这是一个使用示例:

.as-console-wrapper { max-height: 100% !important; top: 0; }

输出:

#include <iostream>
#include <QTextBoundaryFinder>
#include <QString>

int main()
{
    const QString s=QString::fromUtf8(u8"abc\U00010139def\U00010102g");
    std::cout << "String: \"" << s.toStdString() << "\"\n";
    std::cout << "Code unit count       : " << s.length() << "\n";

    QTextBoundaryFinder tbf(QTextBoundaryFinder::Grapheme, s);
    int count=0;
    while(tbf.toNextBoundary()!=-1)
        ++count;
    std::cout << "Grapheme cluster count: " << count << "\n";
}

答案 1 :(得分:2)

我认为你需要使用特定的fromUtf8 static method构建它:

QString s = QString::fromUtf8("Schöne Grüße");