加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:19:19 所属栏目:Java 来源:网络整理
导读:在页面显示的时候,有时候文字无法显示完全,就只能显示部分文字,但是直接截取就只能截取等长字符串,英文和中文很难处理 所以就写了下面方法,截取等长字符 复制代码 代码如下: public static void main(String[] args) { String str = "20120131:《回家》
在页面显示的时候,有时候文字无法显示完全,就只能显示部分文字,但是直接截取就只能截取等长字符串,英文和中文很难处理
所以就写了下面方法,截取等长字符
复制代码 代码如下:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读