求解 C++处理包含中文的字符串问题!

agustins 2017-08-21 12:34:42
问题描述
运行下面代码得到的结果:
周玥座位 length长度为: 5
中国人123 length长度为: 6
上海 length长度为: 2
北漂 length长度为: 2
一般的汉字都能识别,比如“上海”,识别的长度为2,但是“周玥座位” 得到长度为5,把“玥”识别成了2个长度了。目标是中文识别一个长度。针对于这种情况,请教大神怎么处理?

#include <cstring>
#include <iostream>
#include <string>

using namespace std;
int gbk_strlen(const char* str);

main()
{
string str[4] = {"周玥座位","中国人123","上海","北漂"};

for (int i = 0; i < sizeof(str); i++) {

char p[20];
strcpy(p,str[i].data());
int strLength=gbk_strlen(p);
cout<<str[i]+" length长度为: ";
cout<<strLength<<endl;
}
}

int gbk_strlen(const char* str)
{
const char* p = str; //p用于后面遍历

while(*p) //若是结束符0,则结束循环
{

if(*p < 0 && (*(p+1)<0 || *(p+1) < 63)) //中文汉字情况
{
str++; //str移动一位,p移动移动2位,因此长度加1
p += 2;
}
else
{
p++; //str不动,p移动一位,长度加1
}
}
return p-str; //返回地址之差
}
...全文
460 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2017-08-23
  • 打赏
  • 举报
回复
1楼正解,其余都不用看了。
ID870177103 2017-08-23
  • 打赏
  • 举报
回复
对了还需要看看mbstowcs_s和wcstombs_s
ID870177103 2017-08-23
  • 打赏
  • 举报
回复
学习下C++11的<codecvt>,将gbk转为utf16
  • 打赏
  • 举报
回复
最简单的方法,用MultiByteToWideChar转换后求串长度,非要自己求,用IsDBCSLeadByteEx逐字节测试,是的话指针加2,否则指针加1,计数,直到串终止。
赵4老师 2017-08-21
  • 打赏
  • 举报
回复
仅供参考:
//凡是?。!后面跟1~1000后面跟半角.的,在?。!后面加回车换行。
//in.txt:
//1.测试。2.测试2?3.测试3!4.测试
//四。5.测试。6.测试6?7.测试3!8.测试
//运行该程序将输出重定向到比如out.txt即可将输出保存到文件out.txt中
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;
int main() {
    wifstream wifs("in.txt");
    wifs.imbue(locale("chs"));
    wstring wstr(L""),wln;
    while (wifs) {
        getline(wifs,wln);
        wstr+=wln;
    }
    wifs.close();
    wcout.imbue(locale("chs"));
    wcout << wstr << endl;

    wstring rs = L"([?。!])(\\d{1,3}\\.)";
    wregex expression(rs);
    wstr = regex_replace(wstr, expression, wstring(L"$1\r\n$2"));
    wcout << wstr << endl;

    return 0;
}
//1.测试。2.测试2?3.测试3!4.测试四。5.测试。6.测试6?7.测试3!8.测试
//1.测试。
//2.测试2?
//3.测试3!
//4.测试四。
//5.测试。
//6.测试6?
//7.测试3!
//8.测试
//

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧