這一段程式是好久之前有需要時去找到的

剛好有需要用到的東東所以就記了下來

主要是用System.Globalization.UnicodeCategory(定義字元Unicode分類)

將字串轉成Unicode字元陣列後開始讀取

    protected void Page_Load(object sender, EventArgs e)
{
//讀取字串有多少Byte
//string tByte = "中文chk%%";
//Response.Write(System.Text.Encoding.Default.GetBytes(tByte).Length);

//呼叫GetTrim
string str = "sA中文字Abc字";
Response.Write(GetTrim(str,0,5));
}

///
/// 依Byte讀取字串
///
/// 被讀取的字串
/// 開始位置
/// 讀取多少Byte
/// 回傳字串
private string GetTrim(string strVal, int sIndex, int length)
{
//轉成Unicode字元陣列
char[] cArray = strVal.ToCharArray();
string returnValue = "";
int returnLen = 0;
int index = 0;
int i = 0;

while (index < (startIndex + length))
{
char ch = cArray[i];
System.Globalization.UnicodeCategory category = char.GetUnicodeCategory(ch);
if (category == System.Globalization.UnicodeCategory.OtherLetter)
index += 2;
else
index += 1;

if (index >= (startIndex + 1))
{
if (category == System.Globalization.UnicodeCategory.OtherLetter)
returnLen += 2;
else
returnLen += 1;

if (returnLen <= length)
returnValue += ch.ToString();
}
i++;
}
return returnValue;
}
arrow
arrow
    全站熱搜

    鴨爸 發表在 痞客邦 留言(0) 人氣()