我會強烈建議使用UTF-8內部在你的應用程序,使用普通的舊char*
或std::string
用於數據存儲。爲了與使用不同編碼(ASCII,UTF-16等)的API接口,我建議使用libiconv,它是根據LGPL許可的。
用法示例:
class TempWstring
{
public:
TempWstring(const char *str)
{
assert(sUTF8toUTF16 != (iconv_t)-1);
size_t inBytesLeft = strlen(str);
size_t outBytesLeft = 2 * (inBytesLeft + 1); // worst case
mStr = new char[outBytesLeft];
char *outBuf = mStr;
int result = iconv(sUTF8toUTF16, &str, &inBytesLeft, &outBuf, &outBytesLeft);
assert(result == 0 && inBytesLeft == 0);
}
~TempWstring()
{
delete [] mStr;
}
const wchar_t *Str() const { return (wchar_t *)mStr; }
static void Init()
{
sUTF8toUTF16 = iconv_open("UTF-16LE", "UTF-8");
assert(sUTF8toUTF16 != (iconv_t)-1);
}
static void Shutdown()
{
int err = iconv_close(sUTF8toUTF16);
assert(err == 0);
}
private:
char *mStr;
static iconv_t sUTF8toUTF16;
};
iconv_t TempWstring::sUTF8toUTF16 = (iconv_t)-1;
// At program startup:
TempWstring::Init();
// At program termination:
TempWstring::Shutdown();
// Now, to convert a UTF-8 string to a UTF-16 string, just do this:
TempWstring x("Entr\xc3\xa9""e"); // "Entrée"
const wchar_t *ws = x.Str(); // valid until x goes out of scope
// A less contrived example:
HWND hwnd = CreateWindowW(L"class name",
TempWstring("UTF-8 window title").Str(),
dwStyle, x, y, width, height, parent, menu, hInstance, lpParam);
你是什麼意思 「處理Unicode字符串」?你只是想要一些可以存儲一系列Unicode代碼點的東西嗎?正確處理文化特定歸類的東西?一些能夠處理規範和非規範形式的字符串的東西? – jalf 2010-01-10 17:27:56
@jalf好點!我忘了提及我故意排除高級字符串用法,如字符串修改或規範化形式,排序。我認爲,爲了簡單起見,我只會使用這些字符串進行顯示(但我可能需要使用printf格式或字符串並置,但不會更多)。除此之外的任何內容都需要ICU或其他庫。 – sorin 2010-01-10 17:42:40