Java随记2

String str = "s是首发式fssf还ihsifh";
  System.out.println(sprit(str, 5));
 }

 /**
  * 截取汉字的程序 按照字节数截取 一个汉字2个字节,如输入: s是首发式fssf还ihsifh 截取3个字节 则应该打印s是
  *
  * @param str
  * @param a
  * @return
  */
 public static String sprit(String str, int a) {
  int index = 0;
  try {
   byte[] bytes = str.getBytes("GBK");
   boolean falg = false;
   for (int i = 0; i < a; i++) {
    if (bytes[i] < 0 && !falg) {
     falg = true;
    } else {
     index++;
     falg = false;
    }
   }
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
  return str.substring(0, index);
 }

posted @ 2011-10-24 22:22  常伟华  阅读(151)  评论(0编辑  收藏  举报