编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
public
class
test
{
public static void main(String [] args){
test a = new test();
System.out.println( " [ " + a.subByteString( " 我ABC " , 4 ) + " ] " );
System.out.println( " [ " + a.subByteString( " 我ABC汉DEF " , 6 ) + " ] " );
System.out.println( " [ " + a.subByteString( " 我ABC汉DEF " , 7 ) + " ] " );
System.out.println( " [ " + a.subByteString( " 我ABC汉DEF " , 8 ) + " ] " );
}
public String subByteString(String str, int length){
byte [] bt = str.getBytes();
if (bt[length] < 0 ){
length -- ;
}
byte [] nbt = new byte [length];
for ( int i = 0 ;i < length;i ++ ){
nbt[i] = bt[i];
}
return new String(nbt);
}
}
{
public static void main(String [] args){
test a = new test();
System.out.println( " [ " + a.subByteString( " 我ABC " , 4 ) + " ] " );
System.out.println( " [ " + a.subByteString( " 我ABC汉DEF " , 6 ) + " ] " );
System.out.println( " [ " + a.subByteString( " 我ABC汉DEF " , 7 ) + " ] " );
System.out.println( " [ " + a.subByteString( " 我ABC汉DEF " , 8 ) + " ] " );
}
public String subByteString(String str, int length){
byte [] bt = str.getBytes();
if (bt[length] < 0 ){
length -- ;
}
byte [] nbt = new byte [length];
for ( int i = 0 ;i < length;i ++ ){
nbt[i] = bt[i];
}
return new String(nbt);
}
}
大代码测试结果:
[我AB]
[我ABC]
[我ABC汉]
[我ABC汉D]
不知道思路是否正确,方法是否正确,是否有BUG,还请各位高手,多多指教!