关于字符串的截取

    转自http://zangweiren.iteye.com/blog/216005
public static void main(string []args) throws exception
   {
  system.out.println(substring("我dominic爱java",10));
   }
public static string substring(string orignal, int count)
   throws unsupportedencodingexception {
   // 原始字符不为null,也不是空字符串
   if (orignal != null && !"".equals(orignal)) {
   // 将原始字符串转换为gbk编码格式
   orignal = new string(orignal.getbytes(), "gbk");
   // 要截取的字节数大于0,且小于原始字符串的字节数
   if (count > 0 &amp;&amp; count < orignal.getbytes("gbk").length) {
   stringbuffer buff = new stringbuffer();
   char c;
   for (int i = 0; i < count; i++) {
   // charat(int index)也是按照字符来分解字符串的
   c = orignal.charat(i);
   buff.append(c);
   if (ischinesechar(c)) {
   // 遇到中文汉字,截取字节总数减1
   --count;
   }
   }
   return buff.tostring();
   }
   }
   return orignal;
   }
   public static boolean ischinesechar(char c)
   throws unsupportedencodingexception {
   // 如果字节数大于1,是汉字
   // 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了
   return string.valueof(c).getbytes("gbk").length > 1;
   } 

猜你喜欢

转载自lucene321.iteye.com/blog/1140872