Created
December 10, 2012 06:18
-
-
Save zhangw/4248786 to your computer and use it in GitHub Desktop.
Truncate String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// 根据字符长度截断字符串 | |
/// </summary> | |
/// <param name="str"> | |
/// 需要截断的字符串 | |
/// </param> | |
/// <param name="maxLength"> | |
/// 字符串允许的最大长度(包含的byte数) | |
/// </param> | |
/// <param name="isDetectChinese"> | |
/// 是否处理中文字符(把中文字符当作两个byte进行处理) | |
/// </param> | |
/// <param name="endstring"> | |
/// 截断后,新字符串的末尾显示,比如... | |
/// </param> | |
/// <returns> | |
/// 截断后的字符串 | |
/// </returns> | |
public static string Truncate(this string str, int maxLength, bool isDetectChinese=true, string endstring="...") | |
{ | |
str = str.Default(); | |
if (!isDetectChinese) | |
return str.Substring(0, Math.Min(maxLength, str.Length)) + endstring.Default(); | |
else | |
{ | |
Regex reg = new Regex("[\u4e00-\u9fa5]"); | |
var _str = reg.Replace(str, "ch");//use "ch" replace the chinese char | |
if (_str.Length > maxLength) | |
{ | |
int index = maxLength / 2;//the chinese char is 2 byte,but the index value is 1 | |
for (int i = index, l = str.Length; i < l; i++) | |
{ | |
var _length = reg.Replace(str.Substring(0, i), "ch").Length; | |
if (_length >= maxLength) | |
{ | |
return str.Substring(0, i + maxLength - _length) + endstring.Default(); | |
} | |
} | |
} | |
return str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment