2011年7月6日

【C#】Truncate the string

當字串太長時,若要擷取某一部份的字串時,通常會使用
String.substring(int32 a, int32 b)方法,從第
a個位置開始,取得長度為6的字串。
但若是中英夾雜的字串,用此方法可能會擷到中文字的一
字元,此時就需另一個判斷方式。


string str = "I'am 中文字";
int maxLength = 8; //擷取長度為7byte的字串
string result='';
int count = 0;
foreach(char a in str)
{
     counter = counter+ System.Text.Encoding.GetEncodeing("Big5").GetBytes(str.ToString()).Length;
     if(count <= maxLength)
     {
            result = result + a;
     }
     else
     {
            break;
     }
}
System.Writeline(result+"...");


程式中的System.Text.Encoding.GetEncodeing("Big5").GetBytes(str.ToString()).Length;
視字串編碼為定,有些中文字會用UTF-8編碼,則使用GetEncodeing("utf-8");

參考文章:

沒有留言: