c计算utf8字符串的长度,中文算一个字符

#include <iostream>
using namespace std;
int getStrLenUtf8(const char* str)
{
	if (!str) return 0;

	int len = (int)strlen(str);

	int ret = 0;

	for (const char* sptr = str; (sptr - str) < len && *sptr;)
	{
		unsigned char ch = (unsigned char)(*sptr);

		if (ch < 0x80)
		{
			sptr++;	// ascii
			ret++;
		}
		else if (ch < 0xc0)
		{
			sptr++;	// invalid char
		}
		else if (ch < 0xe0)
		{
			sptr += 2;
			ret++;
		}
		else if (ch < 0xf0)
		{
			sptr += 3;
			ret++;
		}
		else
		{
			// 统一4个字节
			sptr += 4;
			ret++;
		}
	}

	return ret;
}

int main()
{    
	char* str = "我司12sdfsd";
	cout << getStrLenUtf8(str) << endl;
	system("pause");
	return 0;
}
发布了43 篇原创文章 · 获赞 1 · 访问量 2330

猜你喜欢

转载自blog.csdn.net/lpl312905509/article/details/94125952
今日推荐