混合字符串的截取:
最近面试遇到一题目:将混合字符串按照指定的字节进行截取,如“我ABC汉CED”截取四个字节,但是汉字不能截取半个出来,如将上面字符串截取6个字节,应该显示“我ABC”,而不是“我ABC”+“汉”字的半个,请编写程序实现。
package test;
public class Equ {
public static void getStr(String str,int bytes){
int bytesCount = 0; //Bytes Count
int tgps = 0; //Target Position
for(int i=0;i<();i++){ //Split the String and get the bytes of each character
String tmpStr = (i,i+1);
bytesCount += ().length;
if(bytesCount <= bytes){ //if total bytes less than the bytes required then target position plus 1
tgps++;
}
}
((0,tgps)); // Print out the result
}
public static void getStr1(String str,int bytes){
int c[] = new int[().length];
for(int i = 0,j=0;i<; i++){
c[i] = j;
if((j) > 500){ //The ASCII Code for Chinese character is greater than 500 at least
c[++i] = j;
}
j++;
}
((0,c[bytes]));
}
public static void getStr2(String str,int bytes){
int offset = 0;
int tgps = 0;
for(int i=0;i<();i++){
char ch = (i);
int t = ch & 0xff00;//Chinese Character 2 Bytes, which is divided into two parts,
//that is higher bits and Lower bits,if the Character is Chinese the high part
//must be greater than 1;
if(t > 0){
offset += 2;
}else{
offset++;
}
if(offset <= b
字符串的截取 来自淘豆网www.taodocs.com转载请标明出处.