栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在页面显示的时候,有时候文字无法显示完全,就只能显示部分文字,但是直接截取就只能截取等长字符串,英文和中文很难处理
所以就写了下面方法,截取等长字符
复制代码 代码如下:
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 ) + ".." ; 
 }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152769.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号