从字符串中截取等长字节的Java代码
时间:2021-06-01 08:52:16|栏目: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 ) + ".." ;
}
上一篇:通过代理类实现java连接数据库(使用dao层操作数据)实例分享
栏 目:JAVA代码
下一篇:springboot整合mybatis-plus代码生成器的配置解析
本文标题:从字符串中截取等长字节的Java代码
本文地址:http://www.codeinn.net/misctech/133105.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




