如何获得std :: string的准确长度? [英] How to get the accurate length of a std::string?

查看:153
本文介绍了如何获得std :: string的准确长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修剪长的 std :: string ,以使用此代码将其放入文本容器中.

I am trimming a long std::string to fit it in a text container using this code.

std::string AppDelegate::getTrimmedStringWithRange(std::string text, int range)
{
    if (text.length() > range)
    {
        std::string str(text,0,range-3);
        return str.append("...");
    }
    return text;
}

,但是在其他语言(例如 HINDIहिन्दी" )的情况下, std :: string 的长度是错误的.

but in case of other languages like HINDI "हिन्दी" the length of std::string is wrong.

我的问题是如何在所有测试用例中检索std :: string的准确长度.

My question is how can i retrieve accurate length of the std::string in all test cases.

谢谢

推荐答案

假设您使用的是UTF-8,则可以将字符串转换为简单的(hah!)Unicode并计算字符数.我从 rosettacode 中获取了这个示例.

Assuming you're using UTF-8, you can convert your string to a simple (hah!) Unicode and count the characters. I grabbed this example from rosettacode.

#include <iostream>
#include <codecvt>
int main()
{
    std::string utf8 = "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; // U+007a, U+00df, U+6c34, U+1d10b
    std::cout << "Byte length: " << utf8.size() << '\n';
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
    std::cout << "Character length: " << conv.from_bytes(utf8).size() << '\n';
}

这篇关于如何获得std :: string的准确长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆