gpt4 book ai didi

c++ - 如何使用 C++ 计算文本中 Unicode 字符的数量

转载 作者:行者123 更新时间:2023-11-30 02:55:09 25 4
gpt4 key购买 nike

我写了一个简单的代码来计算文本中不同字符的数量。这是下面的代码:

#include <iostream>
#include <fstream>
#include <map>
using namespace std;
const char* filename="text.txt";
int main()
{
map<char,int> dict;
fstream f(filename);
char ch;
while (f.get(ch))
{
if(!f.eof())
cout<<ch;
if (!dict[ch])
dict[ch]=0;
dict[ch]++;
}
f.close();
cout<<endl;
for (auto it=dict.begin();it!=dict.end();it++)
{
cout<<(*it).first<<":\t"<<(*it).second<<endl;
}
system("pause");
}

程序对ascii字符的统计效果很好,但是对汉字等Unicode字符就不能用了,如果要用Unicode字符,怎么解决?

最佳答案

首先,你想数什么? Unicode 代码点或字素簇,即编码意义上的字符,或读者感知的字符?还要记住,“宽字符”(16 位字符)不是 Unicode 字符(UTF-16 和 UTF-8 一样是可变长度!)。

无论如何,获取诸如 ICU 之类的库来执行实际的代码点/集群迭代。为了进行计数,您需要将 map 中的 char 类型替换为适当的类型(代码点为 32 位 unsigned int,或规范化字符串为字素簇,归一化应该 - 再次 - 由图书馆处理)

重症监护病房:http://icu-project.org

字素簇:http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries

归一化:http://unicode.org/reports/tr15/

关于c++ - 如何使用 C++ 计算文本中 Unicode 字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653769/

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