String字符串截取(判断是否是汉字str.getByteS())

import java.io.UnsupportedEncodingException;

//编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串
//但要保证汉子不能被截取办个,如"我ABC",4,应该截取"我AB"
//输入"我ABC汉DEF",6,应该截取"我ABC",不能出现半个字
public class StringTest {

public static int trimGBK(byte[] buf,int n){
int num = 0;
boolean bChineseFirstHalf = false;
for(int i=0;i<n;i++){
if(buf[i]<0&&!bChineseFirstHalf){
bChineseFirstHalf = true;
}else{
num++;
bChineseFirstHalf = false;
}

}
return num;
}

public static void main(String[] args) throws UnsupportedEncodingException {
String str ="我a爱中华abc我爱def";
//String str ="我ABC汉";
int num = trimGBK(str.getBytes("GBK"),5);
System.out.println(str.substring(0, 5));
}

}



附加:

String a = new String("我是一串含有中文的字符串");然后对byte[] b = a.getBytes();转化为字节类型的数组,

1
2
3
4
5
6
7
8
9
10
11
12
13
public  class  Test{
     public  static  void  main(String[] args) {
         String a =  new  String( "hw,mmmm字符串" );
         byte [] b = a.getBytes();
         for ( int  i =  0 ,m=b.length;i<m;i++){
             if (b[i] >=  0  && b[i] <= 127 ){ //10进制ascill表0到127
                 System.out.println(b[i]+ ":我是字母数字或者符号" );
             } else {
                 System.out.println(b[i]+ ":我是中文日文或者韩文,反正键盘上不能直接看到我" );
             }
         }
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值