_java Java code that intercepts equal-length bytes from a string

Source: Internet
Author: User
When the page is displayed, sometimes the text can not be displayed completely, can only display part of the text, but the direct interception can only intercept the long string, English and Chinese difficult to deal with
So I wrote the following method, intercept the equal length character
Copy Code code as follows:

public static void Main (string[) args) {

  string str = "20 120131: "Home" 1 Hello ";

  system.out.println (subString (str, 10));
 }
 public static string subString (string str, int len) {
  len *= 2;
  byte[]bytes = Str.getbytes ();
  if (bytes.length <= len) {
   return str;
  }

  byte[]newbytes = arrays.copyof (bytes, Len);
  int count = 0;
  for (Byte b:newbytes) {
   if (b < 0) {
    count++;
   }
  }
  if (count% 2!= 0) {

   len + +;
   newbytes = arrays.copyof (bytes, Len);
  }

 
  return new String (newbytes) + "..."; 
 

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.