黑马程序员技术交流社区
标题:
编写函数,从一个字符串中按字节数截取一部分,但不能截取出半个中文(GBK码表)
[打印本页]
作者:
想要那片海
时间:
2015-5-1 21:27
标题:
编写函数,从一个字符串中按字节数截取一部分,但不能截取出半个中文(GBK码表)
/*
第10题:编写函数,从一个字符串中按字节数截取一部分,但不能截取出半个中文(GBK码表)
例如:从“HM程序员”中截取2个字节是“HM”,截取4个则是“HM程”,截取3个字节也要是"HM"而不要出现半个中文
分析:
1、首先将字符串转换成字节数组,可以自定义获取字节个数进行字节的获取
2、按照要求不能获取半个中文,因为在GBK编码表中对应的汉字是用复数表示的,所以可以根据获取到最后一个字节在GBK中的编码是否小于0进行判断,
如果小于0,则将最后一个字节忽略,进行输出
拓展思路:
结合集合、流 进行拓展练习
1、从键盘录入获取字符串以及要截取的字符个数,以输入over结束输入,
2、对获取的信息封装成Informations对象,存储进List集合中
3、调用方法对字符串进行截取,判断如果最后一个字节为负数且倒数第二个字符不为负数,则最后一个字节为半个中文,这时只截取数-1,
截取到的字节就能转成有效的字符串,而不会出现乱码的情况;
4、将截取后的字符串也存储进集合,通过遍历集合的输出最终的截取结果
*/
import java.io.*;
import java.util.*;
//定义一个Informations类,用来将获取到的键盘输入信息封装成对象
class Informations
{
private String str;
private int len;
Informations(String str,int len)
{
this.str=str;
this.len=len;
}
public String getString()
{
return this.str;
}
public int getLen()
{
return this.len;
}
public String toString()
{
return this.str+","+(this.len+"");
}
}
class Test10
{
public static void main(String[] args)
{
System.out.println("请按照 \"字符串,截取字节个数\" 的形式输入信息,输入over结束:");
getInfoAndGetParts();//调用字符串截取字节方法
}
//定义一个截取键盘录入信息,实现字节截取的方法
public static void getInfoAndGetParts()
{
//通过键盘录入获取字符串
BufferedReader bufr=null;
try
{
List<Informations> infoList= new ArrayList<Informations>();//定义一个集合来存储键盘输入的信息
Informations inf=null;
bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=bufr.readLine())!=null)
{
if("over".equals(line))//定义键盘输入以over结束
break;
else
{
String[] in=line.split(",");
inf=new Informations(in[0],Integer.parseInt(in[1]));
infoList.add(inf);//将Informations对象存储进List列表
}
}
List<String> st=getParts(infoList);//对列表中的信息进行字节截取
for(String ss:st)//对集合进行遍历
{
System.out.println("截取字节后的有效字符串是:"+ss);
}
}
catch (IOException ioe)
{
System.out.println("截取字符串失败;");
}
finally
{
try
{
if(bufr!=null)
bufr.close();
}
catch (IOException ioe)
{
System.out.println("关闭流失败");
}
}
}
/*定义一个获取制定字节数的方法,接收一个存储信息的数组,一个字符串和截取个数;
通过遍历Informations集合,获取字符串和截取字节个数,进行截取操作;
再将截取后的有效字符串存储进List集合中
*/
public static List<String> getParts(List<Informations> list)
{
Iterator<Informations> it=null;
List<String> partList=new ArrayList<String>();//定义一个List集合用来存储截取后的字符串
byte[] by={};//定义一个数组,存储字符串编码成字节后的数据
String str=null;
int len=0;
try
{
for(Informations infos:list)
{
str=infos.getString();//获取集合中存储的Informations对象的字符串
by=str.getBytes("GBK");//将获取到的集合中的字符串根据GBK编码表转换成字节存如数组中
len=infos.getLen();//获取集合中存储的Informations对象的截取个数值
if(len>by.length)//如果要截取的字节个数超出了字符串范围,返回提示语句
System.out.println("截取长度超出字符串范围");
if(by[len-1]<0 & by[len-2]>0)//如果截取的最后一个字节小于0,并且截取的倒数第二个字节大于0,将截取个数-1,相当于只截取前面的有效字节
{
len=len-1;
}
partList.add(new String(by,0,len,"GBK"));
}
}
catch (UnsupportedEncodingException ue)
{
System.out.println("编码转换失败");
}
return partList;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2