C++ utf8字符计数不工作
有人能解释为什么第一个功能有效,而第二个功能无效吗C++ utf8字符计数不工作,c++,unicode,utf-8,C++,Unicode,Utf 8,有人能解释为什么第一个功能有效,而第二个功能无效吗 unsigned int utf8_count(char* in) { unsigned int i = 0, c = 0; while (in[i]) { if ((in[i] & 0xc0) != 0x80) c++; i++; } return c; } unsigned int utf8_count(char* in, unsi
unsigned int utf8_count(char* in)
{
unsigned int i = 0, c = 0;
while (in[i])
{
if ((in[i] & 0xc0) != 0x80)
c++;
i++;
}
return c;
}
unsigned int utf8_count(char* in, unsigned int in_size)
{
unsigned int i = 0, c = 0;
while (i < in_size)
{
if ((in[i] & 0xc0) != 0x80)
c++;
i++;
}
return c;
}
unsigned int utf8\u计数(char*in)
{
无符号整数i=0,c=0;
while(在[i])
{
if((在[i]和0xc0中)!=0x80)
C++;
i++;
}
返回c;
}
无符号整数utf8计数(字符*英寸,无符号整数英寸)
{
无符号整数i=0,c=0;
而(i
我明白什么是(在[I]&0xc0中)!=0x80有,但我不明白为什么I
中
示例字符串:ゴールデンタイムラバー/スキマスイッチ代码>57字节,19个字符
为什么utf8\u计数(in,57)
返回57而不是19
示例字符串的二进制表示形式:
您看到的问题是示例字符串
看看ゴールデンタイムラバー/スキマスイッチ代码>
您的示例字节在空字节前显示18x“00111111”。
根据我的计算,第一个函数应该返回18,第二个函数应该返回更大的数字。您确定传递的字符串正确吗
我认为您在图像中显示的字节与文本ゴールデンタイムラバー/スキマスイッチ代码>(如果只是因为我没有看到同一个字符在这个字符串的开头重复多次的话。在这里工作得非常好
我使用g++4.8.1和MSVC 2013在Windows 8上的两个代码块中进行了测试。在linux上也进行了测试。效果不错。它们都打印了19
所以无论你喂的是什么,它都不是你在OP中的字符串
// UTF8Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <clocale>
int strlen_u8(const char* str)
{
int I = 0, J = 0;
while (str[I])
{
if ((str[I] & 0xC0) != 0x80)
{
++J;
}
++I;
}
return J;
}
int strlen_s_u8(const char* str, unsigned int size)
{
unsigned int I = 0, J = 0;
while (I < size)
{
if ((str[I] & 0xC0) != 0x80)
{
++J;
}
++I;
}
return J;
}
#if defined _MSC_VER || defined _WIN32 || defined _WIN64
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#ifdef _MSC_VER
const char* str = "ゴールデンタイムラバー/スキマスイッチ";
#else
const char* str = u8"ゴールデンタイムラバー/スキマスイッチ";
std::setlocale(LC_ALL, "ja_JP.UTF-8");
#endif
std::cout << strlen_u8(str) << "\n";
std::cout << strlen_s_u8(str, strlen(str)) << "\n"; //can use 57 instead of strlen.
std::cin.get();
}
//UTF8Test.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括
#包括
#包括
int strlen_u8(常量字符*str)
{
int I=0,J=0;
while(str[I])
{
如果((str[I]&0xC0)!=0x80)
{
++J;
}
++一,;
}
返回J;
}
int strlen_s_u8(常量字符*str,无符号整数大小)
{
无符号整数I=0,J=0;
而(I std::cout您在大小中传递的是什么?如果传入strlen(in)
这两个函数是等效的。我以字节为单位传递大小。为什么strlen以字符为单位返回大小?例如:ゴールデンタイムラバー/スキマスイッチ
是57字节或19个字符。@Luka-没有现成的函数返回此计数?您使用的编译器和操作系统是什么?strlen
在示例字符串上应该返回57(或59,无论字节长度是多少),而不是19。名称有点用词不当。它不知道UTF8或任何其他编码;它只是在遇到零值之前计算非零char
值(=字节,通常)。