0%

C++字符串编码转换:ASCII/Unicode/UTF-8

StringConvert.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// StringConvert.h
#ifndef STRINGCONVERT_H_H
#define STRINGCONVERT_H_H
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using std::string;
using std::wstring;

wstring AsciiToUnicode(const string &str);
string AsciiToUtf8(const string &str);

string UnicodeToAscii(const wstring &wstr);
string UnicodeToUtf8(const wstring &wstr);

string Utf8ToAscii(const string &str);
wstring Utf8ToUnicode(const string &str);
#endif

StringConvert.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// StringConvert.cpp

#include "stdafx.h"
#include "StringConvert.h"

wstring AsciiToUnicode(const string &str)
{
//得到str的字节数
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
wchar_t *wstr = new wchar_t[sizeof(wchar_t) * len];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wstr, len);
wstring destr = wstr;
delete[] wstr;
return destr;
}

string AsciiToUtf8(const string &str)
{
wstring wstr = AsciiToUnicode(str);
string destr = UnicodeToUtf8(wstr);
return destr;
}

string UnicodeToAscii(const wstring &wstr)
{
// 得到wstr的自己数
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
char *str = new char[sizeof(char) * len];
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, str, len, nullptr, nullptr);
string destr = str;
delete[] str;
return destr;
}

string UnicodeToUtf8(const wstring &wstr)
{
// 得到wstr的字节数
int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
char *str = new char[sizeof(char) * len];
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, str, len, nullptr, nullptr);
string destr = str;
delete[] str;
return destr;
}

string Utf8ToAscii(const string &str)
{
wstring wstr = Utf8ToUnicode(str);
string destr = UnicodeToAscii(wstr);
return destr;
}

wstring Utf8ToUnicode(const string &str)
{
//得到str的字节数
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
wchar_t *wstr = new wchar_t[sizeof(wchar_t) * len];
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wstr, len);
wstring destr = wstr;
delete[] wstr;
return destr;
}