一道JAVA编程面试题,拿来做了一下。
题目:
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,
输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
public
class
splitString
... {
public void split(String s,int len)
...{
String result="";
int counter=0,i=0;
char temp;
while(counter<len)
...{
temp=s.charAt(i);
if(Character.getNumericValue(temp)!=-1)
...{
result=result+temp;
counter++;
i++;
}
else
...{
result=result+temp;
counter=counter+2;
i++;
}
}
if(counter>len) //去掉多出的半个中文字节
...{
if(len==1)
...{
result="";
}
else...{
result=result.substring(0,counter-3);
}
}
System.out.println(result);
}
public splitString()
...{}
public static void main(String[] args)
...{
splitString test=new splitString();
String a="我我ABCD";
test.split(a,3);
}
}
... {
public void split(String s,int len)
...{
String result="";
int counter=0,i=0;
char temp;
while(counter<len)
...{
temp=s.charAt(i);
if(Character.getNumericValue(temp)!=-1)
...{
result=result+temp;
counter++;
i++;
}
else
...{
result=result+temp;
counter=counter+2;
i++;
}
}
if(counter>len) //去掉多出的半个中文字节
...{
if(len==1)
...{
result="";
}
else...{
result=result.substring(0,counter-3);
}
}
System.out.println(result);
}
public splitString()
...{}
public static void main(String[] args)
...{
splitString test=new splitString();
String a="我我ABCD";
test.split(a,3);
}
}