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));
}
//编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串
//但要保证汉子不能被截取办个,如"我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
{
}
}
}
}
|