萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 精確計算混合中英文字串的位元組長度 (三種編碼方案對比)

問題背景

中文字元在不同編碼下位元組長度不同:

  • UTF-8: 3 位元組 (BMP 字符)
  • UTF-16 (Unicode/.NET 內部): 2 位元組 (BMP)、4 位元組 (補充平面)
  • GB2312/GBK: 2 位元組
  • Big5: 2 位元組
  • ASCII/預設 ANSI: 中文會變成 ? (0x3F),資訊遺失

**「字串長度」無絕對答案,必須指定編碼。**

方案一:指定編碼直接取位元組長度 (推薦)

public static int GetByteLength(string text, Encoding encoding = null) {
    if (string.IsNullOrEmpty(text)) return 0;
    encoding ??= Encoding.UTF8; // 預設 UTF-8
    return encoding.GetByteCount(text);
}

// 使用範例
string s = "I Love 北京!";
Console.WriteLine($"UTF-8: {GetByteLength(s, Encoding.UTF8)}");      // 13
Console.WriteLine($"UTF-16: {GetByteLength(s, Encoding.Unicode)}");  // 24 (含 BOM 需 -2)
Console.WriteLine($"GBK: {GetByteLength(s, Encoding.GetEncoding("gb2312"))}"); // 14
Console.WriteLine($"Default(ANSI): {GetByteLength(s, Encoding.Default)}"); // 視系統地區而定

方案二:手工模擬「中文 2 字節、英文 1 字節」邏輯 (傳統需求)

某些舊系統/通訊協定定義「中文佔 2 字節、英文/數字/符號佔 1 字節」,不對應任何標準編碼,需自行實作:

方法 A:ASCII 編碼判斷法 (有缺陷)

public static int GetLegacyByteLength_AsciiCheck(string s) {
    if (string.IsNullOrEmpty(s)) return 0;
    var ascii = Encoding.ASCII.GetBytes(s); // 中文變 0x3F ('?')
    int len = 0;
    foreach (byte b in ascii) {
        len += (b == 0x3F) ? 2 : 1; // 簡單假設:所有非 ASCII 字元視為中文佔 2 字節
    }
    return len;
}

⚠️ **缺陷**:任何非 ASCII 字元 (日文、韓文、Emoji、特殊符號) 都會被算作 2 字節,不準確。

方法 B:Unicode (UTF-16) 字節分析法 (較精確)

public static int GetLegacyByteLength_UnicodeAnalysis(string s) {
    if (string.IsNullOrEmpty(s)) return 0;
    byte[] bytes = Encoding.Unicode.GetBytes(s); // Little-Endian UTF-16
    int len = 0;
    for (int i = 0; i < bytes.Length; i++) {
        if (i % 2 == 0) { // 低位元組 (每個 char 的第一個 byte)
            len++; // 基礎 1 字節
        } else { // 高位元組
            if (bytes[i] > 0) len++; // 高位非零 → 非 ASCII 範圍 → 視為雙字節字元
        }
    }
    return len;
}

原理:UTF-16 LE 中,ASCII 字元高位元組為 0x00;非 ASCII (含中文) 高位元組非零。

方案三:依實際業務編碼標準實作

效能優化建議

  • 熱路徑緩存 Encoding 實例 (靜態唯讀)。
  • 大量字串處理考慮 Span + Encoding.GetBytes 避免分配。
  • 若僅需「顯示寬度」(終端機對齊),請用 StringInfo.LengthInTextElements 或專門的 ConsoleHelper,而非位元組長度。

結語

**永遠明確指定編碼**。除非維護極其古老的固定寬度協定,否則**直接使用 Encoding.GetByteCount()** 最準確、最可維護。拒絕「中文 2 字節、英文 1 字節」的過度簡化假設,擁抱 Unicode 與 UTF-8 統一世界。

copyright © 萬盛學電腦網 all rights reserved
業務標準實作方式
GBK/GB2312Encoding.GetEncoding("gb2312").GetByteCount(s)
Big5Encoding.GetEncoding("big5").GetByteCount(s)
UTF-8Encoding.UTF8.GetByteCount(s)
自定義 (中文2/英文1)遍歷 char,char.IsSurrogatePair 處理補充平面,char.GetUnicodeCategory 判斷類別