Intercepts equal length bytes of Java code from a string

  • 2020-04-01 02:34:27
  • OfStack

In the page display, sometimes the text can not be displayed completely, can only display part of the text, but the direct interception can only intercept the same length of string, English and Chinese is difficult to deal with
So I wrote the following method, intercept equal length characters

public static void main(String[] args) {

  String str = "20120131 "Going home" 1 How are you? " ; 

  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 ) + ".." ;  
 }

Related articles: