posts - 73,  comments - 55,  trackbacks - 0
/*
 * 题目:
 * 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。 
 * 
 * 解释:
 * 此处的编码方式应该是操作系统默认的GB编码,即汉字占2个字节且第一个字节的最高位是1,
 * 如果理解为有符号数的话,就是负数;而英文占1个字节,符合ASC2码。
 
*/

class  SplitString 
{
 
private  String str;
 
private   int  byteNum;

 
public  SplitString() {}

 
public  SplitString(String str, int  byteNum)
 
{
  
this .str = str;
  
this .byteNum = byteNum;

 }

 
 
public   void  splitIt()
 
{

  
byte  bt[] = str.getBytes();
  System.out.println(
" Length of this String ===> " + bt.length);
  
if (byteNum >= 1 )
  
{
   
if (bt[byteNum] < 0 )
   
{
    String substrx
= new  String(bt, 0 , -- byteNum);
    System.out.println(substrx);
   }
else
   
{
    String substrex
= new  String(bt, 0 ,byteNum);
    System.out.println(substrex);
   }

  }
else
  

   System.out.println(
" 输入错误!!!请输入大于零的整数: " );
  }

 }

}


public   class  TestSplitString
{
 
public   static   void  main(String args[])
 
{
  String str
= " 我ABC汉DEF " ;
  
int  num = 6 ;
  SplitString sptstr 
=   new  SplitString(str,num);
  sptstr.splitIt();
 }

}
posted on 2007-03-06 17:17 保尔任 阅读(1675) 评论(1)  编辑  收藏 所属分类: Arithmetic & Data Structure

FeedBack:
# re: java用字节数截取字符串[未登录]
2011-08-26 14:44 | dj
f (bt[byteNum] < 0 )
{
String substrx = new String(bt, 0 , -- byteNum);
System.out.println(substrx);
}
//这样写,存在bug,如果,比如 “中国人”,6, 按你这样,得到的结果就是“中国?”  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

<2007年3月>
25262728123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿(4)

随笔分类

随笔档案

文章分类

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜