| 
 
| package com.itheima; 
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 
 /**
 * 编写函数,从一个字符串中按字节数截取一部分,但不能截取出半个中文(GBK码表),
 * 例如:从“HM程序员”中截取2个字节是“HM”
 * ,截取4个则是“HM程”,截取3个字节也要是"HM"而不要出现半个中文
 * @author Administrator
 *一个GBK汉字要占两个char空间(二字节),
 *而且第一个字节里的值是小于0的。可以据此判断是否为汉字。
 */
 public class Test10 {
 public static void main(String[] args) throws IOException {
 System.out.println(subString("Yes,I am 黑马",12));
 }
 
 /**
 *
 * @param str 要截取的原字符串
 * @param count 截取的字节个数
 * @return resStr 截取后的字符串
 * @throws UnsupportedEncodingException
 */
 
 public static String subString(String str,int key) throws IOException
 {
 //获得str对应 字节数组
 byte[] resbytes = str.getBytes("gbk");
 byte[] bytes =new byte[key];
 for(int i =0;i<key;i++){
 bytes =resbytes;
 }
 //因为中文GBK是返回两个负数,所以从最后一个开始往前遍历
 //如果负数个数为单数,那么为半个中文,舍弃,否则为一个中文,返回
 int count = 0;
 for(int i=0;i<bytes.length;i++)
 {
 if(bytes<0)
 count++;
 else
 continue;
 }
 //如果count为奇数,则最后一位为一个中文字符的第一位
 if(count%2==1){
 return new String(bytes,0,key-1,"gbk");
 }
 
 else{
 return new String(bytes,0,key,"gbk");
 }
 }
 }
 
 
 
 | 
 
1.png
(125.83 KB, 下载次数: 23)
 
 |