洗剑池

 
 Blog首页我的首页 我的文章我的像册我的圈子后台管理给我留言聚合
当前位置:首页-洗剑池->文章内容
中文文章缩略内容截取方法实现
评论数(18) 阅读次数(526)发布时间:2006-12-11 11:40

今天做开发的时候,项目组的一个成员问我怎么截取包括中文内容的指定长度的缩略内容,   于是写了两个方法,随便你用那个测试,给需要的朋友作参考

 /**
     * 截取字符串的前targetCount个字符
     * @param str 被处理字符串
     * @param targetCount 截取长度
     * @param more 后缀字符串
     * @version 0.1
     * @author aithero
     * @return String
     */
    public static String subContentString(String str, int targetCount,String more)
    {
      int initVariable = 0;
      String restr = "";
      if (str == null){
        return "";
      }else if(str.length()<=targetCount){
       return str;
      }else{
     char[] tempchar = str.toCharArray();
     for (int i = 0; (i < tempchar.length && targetCount > initVariable); i++) {
      String s1 = str.valueOf(tempchar[i]);
         byte[] b = s1.getBytes();
         initVariable += b.length;
         restr += tempchar[i];
     }
      }
      if (targetCount == initVariable || (targetCount == initVariable - 1)){
        restr += more;
      }
      return restr;
    }
   
    /**
     * 截取指定文章内容
     * @param str
     * @param n
     * @author aithero
     * @return String
     */
    public static String subContent(String str,int n)
    {
           //格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
      String temp= "";
      if(str.length()<n){//如果长度比需要的长度n小,返回原字符串
       return str;
      }else{
                    int t=0;
                    char[] tempChar=str.toCharArray();
                    for(int i=0;i<tempChar.length&&t<n;i++)
                    {
                            if((int)tempChar[i]>=0x4E00 && (int)tempChar[i]<=0x9FA5)//是否汉字
                            {
                                    temp+=tempChar[i];
                                    t+=2;
                            }
                            else
                            {
                                    temp+=tempChar[i];
                                    t++;
                            }
                    }
                    return (temp+"...");
            }
    }

 
 【评论】 【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   

 
Aboutus | 联系我们 | 程序开发 | 网站地图 | 留言板
Copyright (C) 2005 EasyJF.com, All Rights Reserved
版权所有 简易java框架网
渝ICP备06004507 如有意见请与我们联系 Powered by EasyJFramework