During development, we sometimes encounter too many characters, such as the title of the article. We need to take a certain length and use the ellipsis later. I read a lot of code online and I don't think it is ideal. Because there are Chinese and English characters, Chinese characters are 2 bytes, and English is 1 byte, it is difficult to judge some special characters, such as "☆■♀"And so on. The following is my java code. I made some modifications according to some materials on the Internet.
/***//**
* Specifies the length of the truncated string.
* @ Param Str
* @ Param cutcount: Set the length and number of bytes.
* @ Return
*/
Public static string getsubstr (string STR, int cutcount )...{
If (STR = NULL)
Return "";
String resultstr = "";
Char [] CH = Str. tochararray ();
Int COUNT = CH. length;
Int strblen = Str. getbytes (). length;
Int temp = 0;
For (INT I = 0; I <count; I ++ )...{
Resultstr + = CH [I];
Temp = resultstr. getbytes (). length;
If (temp> = cutcount & temp <strblen )...{
Resultstr + = "...";
Break;
}
}
Return resultstr;
}