检查UTF-8字符串在现代C++中是否有效

stg*_*lov 6 c++ utf-8 surrogate-pairs

众所周知,C++ 11的标准库允许轻松地将字符串从UTF-8编码转换为UTF-16.但是,以下代码成功转换无效的UTF-8输入(至少在MSVC2010下):

#include <codecvt>
#include <locale>
#include <string>

int main() {
    std::string input = "\xEA\x8E\x97" "\xE0\xA8\x81" "\xED\xAE\x8D";
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
    try {
        std::u16string output = converter.from_bytes(input.data());
        printf("Converted successfully\n");
    }
    catch(std::exception &e) {
        printf("Error: %s\n", e.what());
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的字符串包含9个字节,3个代码点.最后一个代码点是0xDB8D,它是无效的(适合代理范围).

是否可以仅使用现代C++的标准库来检查UTF-8字符串的完美有效性?这里我的意思是不允许维基百科文章中描述的所有无效案例.

小智 0

在官方 UTF-8 文档中https://www.ietf.org/rfc/rfc3629.txt

  • 多八位位组序列的第一个八位位组指示序列中的八位位组数量 - 因此您可以确定长度是否正确。
  • 八位字节值 C0、C1、F5 到 FF 永远不会出现 - 因此您检查它们是否出现在 UTF-8 字符串中