c++ - utf-8 中 std::string 的子字符串? C++11

标签 c++ c++11 utf-8 substr stdstring

我需要获取假定为 utf8 的 std::string 中前 N 个字符的子字符串。 我了解到 .substr 无法正常工作……正如……预期的那样。

引用:我的字符串大概是这样的:任务:\n\n1亿2千匹

最佳答案

found这段代码,我正要尝试一下。

std::string utf8_substr(const std::string& str, unsigned int start, unsigned int leng)
{
    if (leng==0) { return ""; }
    unsigned int c, i, ix, q, min=std::string::npos, max=std::string::npos;
    for (q=0, i=0, ix=str.length(); i < ix; i++, q++)
    {
        if (q==start){ min=i; }
        if (q<=start+leng || leng==std::string::npos){ max=i; }

        c = (unsigned char) str[i];
        if      (
                 //c>=0   &&
                 c<=127) i+=0;
        else if ((c & 0xE0) == 0xC0) i+=1;
        else if ((c & 0xF0) == 0xE0) i+=2;
        else if ((c & 0xF8) == 0xF0) i+=3;
        //else if (($c & 0xFC) == 0xF8) i+=4; // 111110bb //byte 5, unnecessary in 4 byte UTF-8
        //else if (($c & 0xFE) == 0xFC) i+=5; // 1111110b //byte 6, unnecessary in 4 byte UTF-8
        else return "";//invalid utf8
    }
    if (q<=start+leng || leng==std::string::npos){ max=i; }
    if (min==std::string::npos || max==std::string::npos) { return ""; }
    return str.substr(min,max);
}

更新:这对我当前的问题很有效。我不得不将它与 get-length-of-utf8encoded-stdsstring 函数混合使用。

我的编译器对这个解决方案发出了一些警告:

Some warnings spit out by my compiler.

关于c++ - utf-8 中 std::string 的子字符串? C++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30995246/

相关文章:

c++ - 监控 OpenCL 内核的进度

c++ - 如果我的项目现在完全在 c++98 上,那么迁移到 c++11 的任何缺点

c++ - 使用外部模板 (C++11)

python - 克罗地亚字符和 python

php - 如何检测哪种类型的中文编码有文本文件?

c++ - 在递增整数索引时迭代容器的惯用方法是什么?

c++ - 嵌入Python 3.3 : How do I access _PyParser_Grammar?

c++ - 如何创建<id, member function>的映射?

c++ std::move 在这里不好吗?

php - preg_match_all 在 PHP 中返回 utf-8 的正确偏移量