从字符串中截取等长字节的Java代码
更新时间:2013年12月13日 16:41:46 作者:
这篇文章主要介绍了从字符串中截取等长字节的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 ) + ".." ;
}
所以就写了下面方法,截取等长字符
复制代码 代码如下:
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 ) + ".." ;
}
相关文章
maven导入本地仓库jar包,报:Could not find artifact的解决
这篇文章主要介绍了maven导入本地仓库jar包,报:Could not find artifact的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-03-03
Java获取Jar、War包路径并生成可编辑修改的本地配置文件
这篇文章主要给大家介绍了关于Java如何获取Jar、War包路径并生成可编辑修改的本地配置文件,文中通过代码介绍的非常详细,对大家学习或者使用Java具有一定的参考借鉴价值,需要的朋友可以参考下2024-01-01


最新评论