gpt4 book ai didi

c++ - 如何测量非ASCII字符的正确大小?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:25 25 4
gpt4 key购买 nike

在下面的程序中,我试图测量具有非 ASCII 字符的字符串的长度。

但是,我不确定为什么 size() 在使用非 ASCII 字符时没有打印出正确的长度。

#include <iostream>
#include <string>

int main()
{
std::string s1 = "Hello";
std::string s2 = "इंडिया"; // non-ASCII string
std::cout << "Size of " << s1 << " is " << s1.size() << std::endl;
std::cout << "Size of " << s2 << " is " << s2.size() << std::endl;
}

输出:

Size of Hello is 5
Size of इंडिया is 18

现场演示 Wandbox .

最佳答案

std::string::size返回字节长度,而不是字符数。您的第二个字符串使用 UNICODE 编码,因此每个字符可能需要几个字节。请注意,这同样适用于 std::wstring::size,因为它将取决于编码(它返回宽字符的数量,而不是实际字符:如果使用 UTF-16,它将匹配但不一定适用于其他编码,更多 in this answer )。

要测量实际长度(符号数),您需要知道编码以便正确分隔(并因此计算)字符。 This answer例如,可能对 UTF-8 有帮助(尽管使用的方法在 C++17 中已弃用)。

UTF-8 的另一个选项是计算第一个字节的数量 ( credit to this other answer ):

int utf8_length(const std::string& s) {
int len = 0;
for (auto c : s)
len += (c & 0xc0) != 0x80;
return len;
}

关于c++ - 如何测量非ASCII字符的正确大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46947317/

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