转载: (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;
}