C++:全角和半角转化

转载: (1条消息) C++全角与半角互转_前进的菜鸟的博客-CSDN博客

转载:C++中的半角、全角字符转换_Peterld的博客-CSDN博客

 重点:

#include <algorithm> 
#include <functional> 
#include <iostream> 
#include <map>
#include <set>
#include <stack>
#include <assert.h>
using namespace std;

string GetStr(string sText)
{
	string tText;
	unsigned char tmp; unsigned char tmp1;
	for (unsigned int i = 0; i < sText.size(); i++)
	{
		tmp = sText[i];
		tmp1 = sText[i + 1];
		if (tmp == 163)
		{
			tText += (unsigned char)sText[i + 1] - 128;
			i++;
			continue;
		}
		else if (tmp > 163)
		{
			tText += sText.substr(i, 2);
			i++;
			continue;
		}
		else if (tmp == 161 && tmp1 == 161)
		{
			tText += "";
			i++;
		}
		//波浪线全角半角需要特殊处理
		else if (tmp == 161 && tmp1 == 171)
		{
			tText += 126;
			i++;
		}
		else
		{
			tText += sText.substr(i, 1);
		}
	}
	return tText;
}

bool FullStrToHalfstr(const string& strFullWidth, string& strHalfWidth)
{
	strHalfWidth.clear();
	unsigned char tmp; unsigned char tmp1;
	for (unsigned int i = 0; i < strFullWidth.length(); i++)
	{
		tmp = strFullWidth[i];
		tmp1 = strFullWidth[i + 1];
		if (tmp == 163)
		{
			strHalfWidth += (unsigned char)strFullWidth[i + 1] - 128;
			i++;
			continue;
		}
		else if (tmp > 163)
		{
			strHalfWidth += strFullWidth.substr(i, 2);
			i++;
			continue;
		}
		else if (tmp == 161 && tmp1 == 161)
		{
			strHalfWidth += "";
			i++;
		}
		else
		{
			strHalfWidth += strFullWidth.substr(i, 1);
		}
	}
	return true;
}

string ToDBS(string str) {
	string result = "";
	unsigned char tmp; unsigned char tmp1;
	for (unsigned int i = 0; i < str.length(); i++) {
		tmp = str[i];
		tmp1 = str[i + 1];
		if (tmp == 163) {///第一个字节是163,标志着是全角字符   
			result += (unsigned char)str[i + 1] - 128;
			i++;
			continue;
		}
		else if (tmp > 163) {//汉字   
			result += str.substr(i, 2);
			i++;
			continue;
		}
		else if (tmp == 161 && tmp1 == 161) {///处理全角空格   
			result += "";
			i++;
		}
		else if (tmp == 161 && tmp1 == 171) {///处理全角空格   
			result += 126;
			i++;
		}
		else {
			result += str.substr(i, 1);
		}
	} return result;
}

int main()
{
	string aa = "~~~~~@@",bb;
	FullStrToHalfstr(aa, bb);
	cout << GetStr(aa)<< endl;
	return 0;
}


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值