C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法
更新時(shí)間:2014年07月30日 11:22:44 投稿:shichen2014
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法,比較實(shí)用的功能,需要的朋友可以參考下
本文實(shí)例講述了C#按字節(jié)數(shù)截取字符串并在后面加上省略號(hào)...的方法,這是一個(gè)自定義的C#函數(shù),函數(shù)的使用說明如下:
<param name="origStr">原始字符串</param> <param name="endIndex">提取前endIdex個(gè)字節(jié)</param> <returns></returns>
函數(shù)代碼如下:
public static string GetSubString(string origStr, int endIndex)
{
if (origStr == null || origStr.Length == 0 || endIndex < 0)
return "";
int bytesCount = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(origStr);
if (bytesCount > endIndex)
{
int readyLength = 0;
int byteLength;
for (int i = 0; i < origStr.Length; i++)
{
byteLength = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(new char[] { origStr[i] });
readyLength += byteLength;
if (readyLength == endIndex)
{
origStr = origStr.Substring(0, i + 1) + "...";
break;
}
else if (readyLength > endIndex)
{
origStr = origStr.Substring(0, i) + "...";
break;
}
}
}
return origStr;
}
以下所示示例也是根據(jù)字節(jié)數(shù)截取字符串的,只是這個(gè)函數(shù)后面不加省略號(hào)……
/// 按字節(jié)數(shù)截取字符串(不帶省略號(hào))
/// </summary>
/// <param name="origStr">原始字符串</param>
/// <param name="endIndex">提取前endIdex個(gè)字節(jié)</param>
/// <returns></returns>
public static string GetSub1String(string origStr, int endIndex)
{
if (origStr == null || origStr.Length == 0 || endIndex < 0)
return "";
int bytesCount = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(origStr);
if (bytesCount > endIndex)
{
int readyLength = 0;
int byteLength;
for (int i = 0; i < origStr.Length; i++)
{
byteLength = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(new char[] { origStr[i] });
readyLength += byteLength;
if (readyLength == endIndex)
{
origStr = origStr.Substring(0, i + 1);
break;
}
else if (readyLength > endIndex)
{
origStr = origStr.Substring(0, i);
break;
}
}
}
return origStr;
}
相關(guān)文章
C#實(shí)現(xiàn)漂亮的數(shù)字時(shí)鐘效果
這篇文章主要介紹了C#實(shí)現(xiàn)漂亮的數(shù)字時(shí)鐘效果,涉及時(shí)間函數(shù)的應(yīng)用及繪圖的方法,需要的朋友可以參考下2014-10-10
C#字符串?dāng)?shù)組轉(zhuǎn)換為整形數(shù)組的方法
這篇文章主要介紹了C#字符串?dāng)?shù)組轉(zhuǎn)換為整形數(shù)組的方法,涉及C#數(shù)組遍歷與轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C#中datagridview的EditingControlShowing事件用法實(shí)例
這篇文章主要介紹了C#中datagridview的EditingControlShowing事件用法,實(shí)例分析了datagridview的EditingControlShowing事件的定義與使用技巧,需要的朋友可以參考下2015-06-06
C#實(shí)現(xiàn)PDF頁(yè)面合并的示例代碼
這篇文章主要為大家介紹了如何利用C#及vb.net來實(shí)現(xiàn)合并PDF頁(yè)面內(nèi)容,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定幫助,感興趣的小伙伴可以了解一下2022-04-04

