一、
#region 根据字节数长度来截取字符串。加省略号。
/// <summary>
/// 根据字节数长度来截取字符串。加省略号。
/// </summary>
/// <param name="value">字符串</param>
/// <param name="length">字节数</param>
/// <returns></returns>
public static String SubByte(object value, int length)
{
if (length < 1)
{
return value.ToString();
}
byte[] bytes = Encoding.Unicode.GetBytes(value.ToString());
int len = bytes.GetLength(0);
if (len > length)
{
int n = 0;
int i = 0;
for (; i < len && n < length; i++)
{
if (i % 2 == 0)
{
n++;
}
else
{
if (bytes[i] > 0)
{
n++;
}
}
}
if (i % 2 == 1)
{
if (bytes[i] > 0)
i = i - 1;
else
i = i + 1;
}
return Encoding.Unicode.GetString(bytes, 0, i) + (bytes.Length > length ? "..." : string.Empty);
}
return value.ToString();
}
#endregion
二、
//文章显示内容和截取的长度设置
public static string StringTruncat(string oldStr, int maxLength, string endWith)
{
if (string.IsNullOrEmpty(oldStr))
// throw new NullReferenceException( "原字符串不能为空 ");
return oldStr + endWith;
if (maxLength < 1)
throw new Exception("返回的字符串长度必须大于[0] ");
if (oldStr.Length > maxLength)
{
string strTmp = oldStr.Substring(0, maxLength);
if (string.IsNullOrEmpty(endWith))
return strTmp;
else
return strTmp + endWith;
}
return oldStr;
}
浙公网安备 33010602011771号