/// <summary> ///intercepts a string of a specified length/// </summary> /// <param name= "str" >the string to intercept</param> /// <param name= "Len" >the length to intercept</param> /// <param name= "Flag" >whether to add ellipses after interception (true Plus, false not added)</param> /// <returns></returns> Public Static stringCutstring (stringStrintLenBOOLflag) { string_outstring =""; int_len =0; for(inti =0; I < Str. Length; i++) { if(Char.converttoutf32 (str, i) >= Convert.ToInt32 ("4e00", -) && char.converttoutf32 (str, i) <= Convert.ToInt32 ("9fff", -) ) {_len+=2; if(_len > Len)//the length of the Intercept, if the last two bytes, does not intercept { Break; } } Else{_len++; } Try{_outstring+ = str. Substring (I,1); } Catch { Break; } if(_len >=Len) { Break; } } if(str! = _outstring && Flag = =true)//determine if ellipses are added{_outstring+="..."; } return_outstring; }
/// <summary> ///intercepts a string of a specified length/// </summary> /// <param name= "str" >the string to intercept</param> /// <param name= "Len" >the length to intercept</param> /// <param name= "Flag" >whether to add ellipses after interception (true Plus, false not added)</param> /// <returns></returns> Public Static stringCutstring (stringStrintLenBOOLflag) {System.Text.ASCIIEncoding ASCII=NewSystem.Text.ASCIIEncoding (); byte[] BTS =ASCII. GetBytes (str); int_len =0; string_outstring =""; for(inti =0; I < BTS. Length; i++) { if((int) Bts[i] = = the)//two characters{len+=2; if(_len > Len)//the length of the Intercept, if the last two bytes, does not intercept { Break; } } Else{len+=1; } Try{_outstring+ = str. Substring (I,1); } Catch { Break; } if(_len >=Len) { Break; } } if(str! = _outstring && Flag = =true)//determine if ellipses are added{_outstring+="..."; } return_outstring; }
/// <summary> ///intercepts a string of a specified length/// </summary> /// <param name= "str" >the string to intercept</param> /// <param name= "Len" >the length to intercept</param> /// <param name= "Flag" >whether to add ellipses after interception (true Plus, false not added)</param> /// <returns></returns> Public Static stringCutstring (stringStrintLenBOOLflag) { if(str = =NULL|| Str. Length = =0|| Len <=0) { return string. Empty; } intL =Str. Length; #regionCalculate lengthintClen =0; while(Clen < len && Clen <l) {//for each encounter with a Chinese, reduce the target length by one. if((int) Str[clen] > -) {len--; } Clen++; } #endregion if(Clen <l) {returnFlag? Str. Substring (0, Clen) +"...": Str. Substring (0, Clen); } Else { returnstr; } }
C # 3 ways to intercept string string lengths