c++ 中文字符处理

来源:互联网 发布:计算机c语言基础知识 编辑:程序博客网 时间:2024/04/29 02:00

今天遇到一道题,要求写一个函数,找出字符串中出现次数最多的字符,给的实例中含有中文字符,看到题目直接用hasp表几分钟就敲出来了,运行出现的结果不对。想了想才发现char、string无法处理中文字符,中文字符在计算机中占两个字节,而char只有一个字节,所以将原来char的地方替换成wchar_t,string替换为wstring,以下是函数源代码

wchar_t findMostAppear(const wstring &str){if(str.length() == 0)return '\0';unordered_map<wchar_t, int> countChar;for(size_t i = 0; i < str.length(); i++)countChar[str[i]]++;unordered_map<wchar_t, int>::iterator it;pair<wchar_t, int> max(L'\0', INT_MIN);for(it = countChar.begin(); it != countChar.end(); it++)if(max.second < (*it).second){max.second = (*it).second;max.first = (*it).first;}return max.first;}

测试时又面临一个问题,中文字符输出到屏幕问题

使用cout 或wcout输出wchar_t类型字符总是输出一个数字二不是字符。

原来想要输出中文字符需要让计算机知道你处在哪个区域(国家),c++中有个locale类就是处理这个的,locale:一种描述区域设置对象的类,此对象用于将特定于文化的信息封装为一组 facet 以共同定义特定本地化环境。locale china("chs"); //在中国地区

创建出一个locale对象后,wcout怎么知道呢,调用wcout成员函数locale imbue(   const locale& _Loc)让wcout知道,这样就能输出中文字符了

int main(){locale china("chs");//使用中文字符wcout.imbue(china);wstring str = L"天工问答,是天工网旗下专业的免费知识问答平台,帮助建设行业从业者解决在学习和工作中遇到的实际问题,让建筑人不再有疑问";wchar_t t = findMostAppear(str);wcout << t << endl;system("pause");return 0;}



0 0
原创粉丝点击