关于字符串的截取

转自http://zangweiren.iteye.com/blog/216005
public static void main(String []args) throws Exception
{
System.out.println(substring("我DOMINIC爱JAVA",10));
}
public static String substring(String orignal, int count)
throws UnsupportedEncodingException {
// 原始字符不为null,也不是空字符串
if (orignal != null && !"".equals(orignal)) {
// 将原始字符串转换为GBK编码格式
orignal = new String(orignal.getBytes(), "GBK");
// 要截取的字节数大于0,且小于原始字符串的字节数
if (count > 0 && count < orignal.getBytes("GBK").length) {
StringBuffer buff = new StringBuffer();
char c;
for (int i = 0; i < count; i++) {
// charAt(int index)也是按照字符来分解字符串的
c = orignal.charAt(i);
buff.append(c);
if (isChineseChar(c)) {
// 遇到中文汉字,截取字节总数减1
--count;
}
}
return buff.toString();
}
}
return orignal;
}
public static boolean isChineseChar(char c)
throws UnsupportedEncodingException {
// 如果字节数大于1,是汉字
// 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了
return String.valueOf(c).getBytes("GBK").length > 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值