Collect Java precise string Truncation

Source: Internet
Author: User
==========================================
The string with... is intercepted to ensure that the length of all characters (2 in Chinese) cannot exceed Max:

Example:
Left ("abcdefg", 7) = "abcdefg"
Left ("abcdefg", 6) = "ABC ..."
Left ("Chinese abcdefg", 9) = "Chinese AB ..."

Package com. crackj2ee. util;

/**
* @ Author Xuefeng, asklxf@163.com
*/
Public class stringutil {

Public static string left (string S, int max ){
Char [] cs = S. tochararray ();
Int COUNT = 0;
Int last = cs. length;
For (INT I = 0; I <CS. length; I ++ ){
If (CS [I] & gt; 255)
Count + = 2;
Else
Count ++;
If (count> MAX ){
Last = I + 1;
Break;
}
}
If (count <= max) // string is short or just the size!
Return S;
// String is too long:
Max-= 3;
For (INT I = last-1; I> = 0; I --){
If (CS [I] & gt; 255)
Count-= 2;
Else
Count --;
If (count <= max ){
Return S. substring (0, I) + "...";
}
}
Return "...";
}
}
......
[Read the full text]

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.