using System;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "ABC中文測試";
Console.WriteLine(TrimForBig5(s, 20, false));
Console.WriteLine(TrimForBig5(s, 8, false));
Console.WriteLine(TrimForBig5(s, 8, true));
Console.Read();
}
/// <summary>
/// 將字串截至Big5編碼下的指定長度
/// </summary>
/// <param name="s">輸入字串</param>
/// <param name="len">指定長度</param>
/// <returns>處理結果</returns>
static string TrimForBig5(string str, int len, bool ellipsis)
{
Encoding big5 = Encoding.GetEncoding("big5");
byte[] b = big5.GetBytes(str);
if (b.Length <= len) //未超長,直接傳回
return str;
else
{
//如果要加刪節號再扣三個字元
if (ellipsis) len -= 3;
string res = big5.GetString(b, 0, len);
//由於可能最後一個字元可能切到中文字的前一碼形成亂碼
//透過截斷的亂碼與完整轉換結果會有出入的原理來偵測
if (!big5.GetString(b).StartsWith(res))
res = big5.GetString(b, 0, len - 1);
return res + (ellipsis ? "..." : "");
}
}
}
}