public class Stringhelper { public static string Getsubstring (string str, int len) { string result = String. empty;//final returned results int bytelen = System.Text.Encoding.Default.GetByteCount (str);//single-byte character length int charlen = str. length;//string length when the character is treated equal int byteCount = 0;// Record read Progress int pos = 0;//Record intercept location if (Bytelen > Len) { for (int i = 0; i < Charlen; i++) { if ( Convert.ToInt32 (str. ToCharArray () [i]) > 255)//calculated by Chinese characters plus 2 ByteCount + = 2; else//by English characters plus 1 ByteCount + = 1;
if (ByteCount > Len)//write down only the last valid location when you exceed it { pos = i; break; } else if (ByteCount = = len)//Make a note of the current location { pos = i + 1; break; } }
if (POS >= 0) result = Str. Substring (0, POS); } else result = str;
return result; }
//<summary> //C # Chinese and English mixed string interception ///</summary> //<param name= "inputstring" ></param> //<param Name= "Length" > displayed character length *2</param> //<returns></ returns> public static string SubString (string inputstring, int length) & nbsp; { byte[] Ping = Encoding.UTF8.GetBytes (inputstring); int Count=encoding.utf8.getbytecount ( InputString); if (count <= length * 2) { return inputstring; } asciiencoding ASCII = new ASCIIEncoding (); int templen = 0; string tempstring = ""; byte[] s = ASCII. GetBytes (inputstring); for (int i = 0; i < s.length; i++) & nbsp; { ////to determine whether it is a Chinese character or a full foot symbol if ((int) s[i] = =) { Templen + = 2; } Else { Templen + = 1; } tempstring + = inputstring.substring (i, 1) ; if (Templen >= Length * 2) break; } return tempstring; }
public static string Getsub (string sub, int length) {//byte[] bytstr = SYSTEM.TEXT.ENCODING.DEFAULT.G Etbytes (sub); if (sub = = null) return string. Empty; int len = length * 2; Aequilatelength is in Chinese and English equal width length, cutlength is the string length to intercept int aequilatelength = 0, cutlength = 0; Encoding Encoding = encoding.getencoding ("gb2312");
string cutstr = Sub. ToString (); int strlength = cutstr.length; byte[] bytes; for (int i = 0; i < strlength; i++) & nbsp; { bytes = Encoding. GetBytes (Cutstr.substring (i, 1)); if (bytes. Length = = 2)//not English Aequilatelength + = 2; Else aequilatelength++;
if (aequilatelength <= len) cutlength + = 1;
if (Aequilatelength > Len) return cutstr.substring (0, cutlength);//+ "..."} return cutstr; }
}
C # Mixed string interception in Chinese and English