您的位置:首页 > 编程语言 > Java开发

根据字节数截取字符串... 分类: java 2009-11-05 19:21 235人阅读 评论(0) 收藏

2009-11-05 19:21 519 查看
package com.test;

public class SubStr {
public static void main(String args[]){
String source= "as他df我的world";

Invoke invoke = new Invoke();
String result = invoke.substring(source, -1);

System.out.println("result : "+result);
}
}
class Invoke {
public String substring(String source, int len){
if(null==source || "".equals(source) || len<=0){
return "";
}

byte[] bt = source.getBytes();
if(bt.length < len){
return source;
}

byte[] bt2 = new byte[len];
System.arraycopy(bt, 0, bt2, 0, len);

int count = 0;
for(int i=0;i<bt2.length;i++){
int temp = (int)bt[i];
if(temp<0){//中文时小于0
count++;//统计中文个数
}
}
if(count%2 != 0){//不等于0时表示中文被截取半个,那么真正截取时应减1
len = len-1;
}

return new String(bt,0,len);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐