首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

ANSI、UTF-8 與 Unicode 字串互轉 Windows API 實現

     編輯:關於C

Windows 平台上字元編碼轉換的核心是 MultiByteToWideChar 與 WideCharToMultiByte 兩個 API。本文提供可直接使用的 std::string/std::wstring 轉換函數,並修正原始碼中常見的緩衝區大小計算與釋放問題。

UTF-8 → Unicode (wstring)

inline std::wstring Utf8ToUnicode(const std::string& str) {
    if (str.empty()) return L"";
    
    int len = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
    if (len <= 0) return L"";
    
    std::wstring wstr(len - 1, L'\0'); // -1 排除結尾 null
    ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wstr[0], len);
    return wstr;
}

Unicode → UTF-8 (string)

inline std::string UnicodeToUtf8(const std::wstring& wstr) {
    if (wstr.empty()) return "";
    
    int len = ::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
    if (len <= 0) return "";
    
    std::string str(len - 1, '\0');
    ::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &str[0], len, nullptr, nullptr);
    return str;
}

關鍵修正點

  • 使用 -1 讓 API 自動計算含終止符的長度,避免手動 strlen 導致的截斷。
  • 直接構造 std::wstring/std::string 並取用 &str[0] 作為輸出緩衝區,省去手動 new/delete 與 memset,杜絕記憶體洩漏。
  • 返回值利用 NRVO/RVO 優化,無額外拷貝開銷。

擴充建議

若需支援 ANSI(系統預設代碼頁),僅需將 CP_UTF8 替換為 CP_ACP 即可復用相同邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved