字符串截取(按指定的字节数)汉字不可以截取半个

package com.interview.demo;
/**
 * 截取字符串     按指定的字节数
 * 汉子不可截取半个    abc中国人    4   输出:abc 而不是abc+半个人
 */
import java.io.UnsupportedEncodingException;
public class WhiltCat{
 public static boolean isChinese(char ch) throws UnsupportedEncodingException{
  return String.valueOf(ch).getBytes("GBK").length>1;
 }
 public static String cutString(String str,int count) throws UnsupportedEncodingException{
  if(str!=null&&!"".equals(str)){
  str = new String(str.getBytes(),"GBK");
   if(count>0&&count<str.getBytes("GBK").length){
    StringBuffer buf = new StringBuffer();
    char c;
    int num = 0;
    for(int i=0;i<str.length()-1;i++){
     c = str.charAt(i);
     //从头扫描每个字符  首先判断是不是汉子 接着判断当前截取的字节数+2是否超过了要截取的字节数,
     //如果超过舍弃截取此汉字;否则加入;
     //
     if(isChinese(c)){
      if(num+2<=count){
       buf.append(c);
       num = num+2;
      }else{
       break;
      }
     }else{
      if(num+1<=count){
      buf.append(c);
      num=num+1;
      }else{
       break;
      }
     }
    }
    return buf.toString();
   }
  }
  return str;
 }
 public static void main(String[] args){
  String str = "到遇到jfr是中hinese";
  try {
   System.out.println(cutString(str,7));
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值