Previously, I made a list of modules on the website. The truncation method used at the beginning was simple, and the String Length attribute was used.
Compare the length of the judgment and definition. If the value is exceeded, it is truncated and the custom suffix "..." is added. If the value is not exceeded, it is displayed completely.
The problem is that different Chinese and English characters may lead to different lengths after intercept.
Later I thought of the CSS truncation, giving the width, and setting overflow: hidden.
In this way, the truncation is neat, but once the length and width of the Chinese and English strings have some errors.
The Chinese characters in the title are easy to be cut and show only a part on the left. Therefore, I want to improve the initial truncation method.
Changed from a post in csdn.
The Code is as follows:
/// <Summary> <br/> // capture the string length <br/> /// </Summary> <br/> /// <Param name = "Input "> String object to be intercepted </param> <br/> // <Param name =" length "> Number of characters to be retained </param> <br/>/ // <Param name = "suffix"> suffix (used to replace the part beyond the length) </param> <br/> // <returns> </returns> <br/> Public static string mysubstring (string input, int length, string suffix) <br/>{< br/> encoding encode = encoding. getencoding ("gb2312"); <br/> byte [] bytearr = en Code. getbytes (input); <br/> If (bytearr. length <= length) return input; </P> <p> int m = 0, n = 0; <br/> foreach (byte B in bytearr) <br/>{< br/> If (n> = length) break; <br/> If (B> 127) m ++; // important step: statistics on the characters whose values in the first p bytes are greater than 127 <br/> N ++; <br/>}< br/> If (M % 2! = 0) n = Length + 1; // if it is not even: It indicates that the end is a double byte character, and the number of truncated digits plus 1 </P> <p> return encode. getstring (bytearr, 0, n) + suffix; <br/>}</P> <p>
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/nextuntil/archive/2010/06/06/5650182.aspx