C# 字串字節長度(byte length)計算[非ASCII算2]
C# 字串字節長度(byte length)計算[非ASCII算2]
資料來源: chatgpt
C#線上編譯: https://dotnetfiddle.net/
code
using System;
class Program
{
public static int Wlen(string val)
{
int length = 0;
foreach (char c in val)
{
length += c <= 0xFF ? 1 : 2; // ASCII ≤ 0xFF 為 1 byte,其餘為 2 byte
}
return length;
}
public static void Main(string[] args)
{
Console.WriteLine("Wlen(\"abc\") :" + Wlen("abc")); // 3
Console.WriteLine("Wlen(\"你好\") :" + Wlen("你好")); // 4
Console.WriteLine("Wlen(\"a你b\") :" + Wlen("a你b")); // 4
}
}
/*
Wlen("abc") :3
Wlen("你好") :4
Wlen("a你b") :4
*/
PS.從下面Js(JavaScript)轉譯過來
function Wlen(val) {
var str = "" + val; // 確保JS將傳入的 val 轉成字串
return str.replace(/[^\x00-\xff]/g, "xx").length;
}
2 thoughts on “C# 字串字節長度(byte length)計算[非ASCII算2]”
相關:
C# 字串字節長度分割/切割(byte length)[非ASCII算2]
C# 中文 字串 長度 字數