欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

从字符串中截取等长字节的Java代码

程序员文章站 2023-12-21 12:49:04
在页面显示的时候,有时候文字无法显示完全,就只能显示部分文字,但是直接截取就只能截取等长字符串,英文和中文很难处理所以就写了下面方法,截取等长字符复制代码 代码如下:pub...
在页面显示的时候,有时候文字无法显示完全,就只能显示部分文字,但是直接截取就只能截取等长字符串,英文和中文很难处理
所以就写了下面方法,截取等长字符
复制代码 代码如下:

public static void main(string[] args) {

  string str = "20120131:《回家》1你好么" ;

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

上一篇:

下一篇: