您的位置:首页 > 其它

今天笔试的几道题

2011-03-09 21:11 453 查看
今天笔试的几道题目,当时由于笔试,没法上机,所以就没写,回来看看,记录下:

package com.split;
/**
* @ClassName: StringSplit
* @author rxzjava@gmail.com
* @date 2011-3-9 下午08:02:55
* 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
* 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,
* 输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
*
*/
public class StringSplit {
public static void main(String[] args) {
String s="ABC汉DEF";
int len=4;
splitStr(s,len);
try {
splitStr2(s,len);
} catch (Exception e) {
e.printStackTrace();
}
}
//方法一:
private static void splitStr(String str, int len) {
String result="";
char temp;
int counter=0;	//取得的字节数
int i=0;
int han=0;	//汉字个数
while(counter<len){
temp=str.charAt(i);
if(Character.getNumericValue(temp)!=-1){
//遇到字母的时候
result=result+temp;
counter++;
i++;
}else{
//遇到汉字的时候,作为unicode字符,汉字的整数值是-1
result=result+temp;
counter=counter+2;
i++;
han = han+1;
}
}
if(counter>len){
if(len==1){
result="";
}else{
result=result.substring(0,counter-(han+1));
}
}
System.out.println("result :"+result.toString());
}

//方法二:
private static void splitStr2(String str, int len) throws Exception{
String result=new String(str.getBytes(),0,len,"GBK");
//System.out.println("===:"+result);
if(!str.startsWith(result)){
result=new String(str.getBytes(),0,len-1,"GBK");
}
System.out.println("结果:"+result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: