C# 字串字節長度分割/切割(byte length)[非ASCII算2]
C# 字串字節長度分割/切割(byte length)[非ASCII算2]
資料來源: chatgpt
C#線上編譯: https://dotnetfiddle.net/
code:
using System;
using System.Text;
using System.Collections.Generic;
public class Program
{
public static string GetSubstringByByteLength(string val, int byteLength)
{
int length = 0; // 計算目前的位元組長度
StringBuilder result = new StringBuilder(); // 用來存放結果字串
foreach (char c in val)
{
int byteCount = c <= 0xFF ? 1 : 2; // 根據字元的位元組數計算
if (length + byteCount > byteLength)
{
break; // 超過指定的位元組長度時退出
}
result.Append(c); // 加入字元到結果字串
length += byteCount; // 累加目前的位元組長度
}
return result.ToString(); // 返回結果字串
}
public static string[] SplitStringByByteLength(string val, int maxByteLength)
{
List<string> segments = new List<string>(); // 用來儲存切割後的字串片段
int length = 0; // 當前位元組長度
StringBuilder currentSegment = new StringBuilder(); // 當前的字串片段
foreach (char c in val)
{
int byteCount = c <= 0xFF ? 1 : 2; // 根據字元的位元組數計算
// 如果加上這個字元後超過最大位元組長度,則將當前片段儲存並重置
if (length + byteCount > maxByteLength)
{
segments.Add(currentSegment.ToString());
currentSegment.Clear(); // 清空當前片段
length = 0; // 重置位元組長度
}
currentSegment.Append(c); // 將字元加入當前片段
length += byteCount; // 增加位元組長度
}
// 最後一段字串需要加到結果中
if (currentSegment.Length > 0)
{
segments.Add(currentSegment.ToString());
}
return segments.ToArray(); // 返回字串陣列
}
public static void Main()
{
string input = "你好中文Hello";
string result = GetSubstringByByteLength(input, 5); // 假設我們要取出 7 個位元組長度的字串
Console.WriteLine(result); // 輸出 "你好"
Console.WriteLine("");
string[] result01 = SplitStringByByteLength(input, 5);
foreach (var segment in result01)
{
Console.WriteLine(segment); // 輸出每個分段字串
}
}
}
/*
你好
你好
中文H
ello
*/
相關:C# 字串字節長度(byte length)計算[非ASCII算2]~Wlen