gpt4 book ai didi

c++ - 检查 UTF-8 字符串在 Qt 中是否有效

转载 作者:IT老高 更新时间:2023-10-28 22:26:47 26 4
gpt4 key购买 nike

在 Qt 中,有没有办法检查字节数组是否是有效的 UTF-8 序列?

看来QString::fromUtf8()默默地抑制或替换无效序列,而不通知调用者有任何序列。这是来自其文档:

However, invalid sequences are possible with UTF-8 and, if any such are found, they will be replaced with one or more "replacement characters", or suppressed.

最佳答案

试试 QTextCodec::toUnicode并通过 ConverterState实例。 ConverterState 有像 invalidChars 这样的成员。虽然它们没有通过 doxygen 记录,但我认为它们是公共(public) API,正如 QTextCodec 文档中提到的那样。

示例代码:

QTextCodec::ConverterState state;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
const QString text = codec->toUnicode(byteArray.constData(), byteArray.size(), &state);
if (state.invalidChars > 0) {
qDebug() << "Not a valid UTF-8 sequence.";
}

关于c++ - 检查 UTF-8 字符串在 Qt 中是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com