c perfectly truncates the string code of Chinese + non chinese

  • 2020-05-07 20:15:13
  • OfStack

 
public static string Truncation(this HtmlHelper htmlHelper, string str, int len) 
{ 
if (str == null || str.Length == 0 || len <= 0) 
{ 
return string.Empty; 
} 
int l = str.Length; 
#region  Calculate the length of the  
int clen = 0; 
while (clen < len && clen < l) 
{ 
// Each encounter 1 , then the target length is reduced 1 .  
if ((int)str[clen] > 128) { len--; } 
clen++; 
} 
#endregion 
if (clen < l) 
{ 
return str.Substring(0, clen) + "..."; 
} 
else 
{ 
return str; 
} 
} 

Related articles: