本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – UTF8编码下的全角字符转半角字符
原文链接:https://www.stubbornhuang.com/1848/
发布于:2021年12月04日 11:58:39
修改于:2021年12月04日 11:58:39

1 C++ UTF8编码下的全角字符转半角字符
如果输入的字符std::string是UTF8编码,因为UTF8字符串长度的不确定性,需要先将UTF8编码的字符串转换为宽字符Unicode编码的字符串,再进行全角到半角字符的转换,具体的转换过程参考以下代码:
#include <iostream>
#include <locale>
#include <codecvt>
std::wstring Std_UTF8ToUnicode(const std::string& utf8Str)
{
std::wstring ret;
try
{
std::wstring_convert< std::codecvt_utf8<wchar_t> > conv;
ret = conv.from_bytes(utf8Str);
}
catch (const std::exception& e)
{
}
return ret;
}
std::string Std_UnicodeToUTF8(const std::wstring& unicodeStr)
{
std::string ret;
try
{
std::wstring_convert< std::codecvt_utf8<wchar_t> > conv;
ret = conv.to_bytes(unicodeStr);
}
catch (const std::exception& e)
{
}
return ret;
}
static std::string DoubleByteCharToSingleByteChar_UTF8(const std::string& srcStr)
{
// 先转成Unicode字符
std::wstring srcStr_Uniocde = Std_UTF8ToUnicode(srcStr);
std::wstring destSrt_Unicode = L"";
std::string dstStr = "";
int tempChar;
int length = srcStr_Uniocde.length();
for (int i = 0; i < length; i++)
{
tempChar = srcStr_Uniocde[i];
if (tempChar == 12288)
{
tempChar = 32;
}
else if (tempChar >= 65281 && tempChar <= 65374)
{
tempChar -= 65248;
}
destSrt_Unicode += tempChar;
}
// 然后将处理过后的全角转半角字符Unicode转utf8
dstStr = Std_UnicodeToUTF8(destSrt_Unicode);
return dstStr;
}
int main()
{
std::string input_str = u8"55555。你好。";
std::string output_str = DoubleByteCharToSingleByteChar_UTF8(input_str);
std::cout << output_str << std::endl;
}
当前分类随机文章推荐
- C++ - std::map - 存储动态指针时正确释放内存 阅读2956次,点赞1次
- C++11 - 委托机制的实现TinyDelegate 阅读783次,点赞0次
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error' 阅读1801次,点赞0次
- C++11/std::atomic - 原子变量(不加锁实现线程互斥) 阅读4217次,点赞1次
- C++ - 使用C++标准库过滤Windows文件名中的非法字符 阅读3247次,点赞1次
- C++ – 字节数组byte[]或者unsigned char[]与bool的相互转换 阅读319次,点赞0次
- C++11 - 使用std::chrono计算程序、函数运行时间 阅读1638次,点赞0次
- C++11 - std::chrono - 使用std::chrono::duration_cast进行时间转换,hours/minutes/seconds/milliseconds/microseconds相互转换,以及自定义duration进行转换 阅读1373次,点赞0次
- C++11 - 封装std::thread,增加子线程启动、暂停、唤起、停止功能 阅读1518次,点赞0次
- C++ - 线程安全的std::cout 阅读1115次,点赞0次
全站随机文章推荐
- OpenCV - linux上编译出现undefined reference to `cv::VideoCapture::VideoCapture()'错误 阅读445次,点赞0次
- 资源分享 - 3D Graphics for Game Programming 英文高清PDF下载 阅读637次,点赞0次
- 资源分享 - GLSL Essentials - Enrich your 3D scenes with the power of GLSL 英文高清PDF下载 阅读1236次,点赞0次
- 书籍翻译 – Fundamentals of Computer Graphics, Fourth Edition,第5章 Linear Algebra中文翻译 阅读621次,点赞2次
- C++11/std::thread - 可作为线程函数的几种方式总结 阅读2645次,点赞1次
- OpenCV - 读取一张图片显示,并将其重写为灰度图 阅读3525次,点赞0次
- 资源分享 - Jim Blinn's Corner - A Trip Down the Graphics Pipeline 英文高清PDF下载 阅读1756次,点赞2次
- 资源分享 - Digital Image Processing , Fourth Edition 英文高清PDF下载 阅读1124次,点赞0次
- 资源分享 - Game Physics Engine Development (First Edition) 英文高清PDF下载 阅读1072次,点赞0次
- 资源分享 - GPU Pro 1 - Advanced Rendering Techniques 英文高清PDF下载 阅读2048次,点赞0次
评论
148