How to intercept String Length Using Java

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.