zoukankan      html  css  js  c++  java
  • 文章摘要显示实现

    原理流程:去掉html所有的标签,返回纯文本字符串-》将纯文本字符串按指定长度截取

     1,去除掉HTML里面所有标签,使用Jsoup开源包

    /**
             * 去除掉HTML里面所有标签,使用Jsoup开源包
             * <p>Title: getTextFromTHML</p>
             * <p>Description: </p>
             * @param htmlStr html标签字符串
             * @return 纯文本
             */
            public static String getTextFromTHML(String htmlStr) {
                Document doc = Jsoup.parse(htmlStr);
                String text = doc.text();
                // remove extra white space
                StringBuilder builder = new StringBuilder(text);
                int index = 0;
                while(builder.length()>index){
                    char tmp = builder.charAt(index);
                    if(Character.isSpaceChar(tmp) || Character.isWhitespace(tmp)){
                        builder.setCharAt(index, ' ');
                    }
                    index++;
                }
                text = builder.toString().replaceAll(" +", " ").trim();
                return text;
            }

    2,将纯文本字符串按指定长度截取

     /**  
             * 判断传进来的字符串,是否  
             * 大于指定的字节,如果大于递归调用
             * 直到小于指定字节数 ,一定要指定字符编码,因为各个系统字符编码都不一样,字节数也不一样 
             *src 传入的字符串
             *cutSize 截取的大小长度
             */ 
            public String cutString(String src,int cutSize) throws Exception{
                int changdu = src.getBytes("UTF-8").length;
                if(changdu > cutSize){
                    src = src.substring(0, src.length()-1);
                    src=cutString(src, cutSize);
                }
                return src;
            }

    maven配置:

    <!-- jsoup -->
            <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.3</version>
        </dependency>
  • 相关阅读:
    CSU 1122
    CSU 1256
    CSU 1240
    HDU 1874
    CSU 1004
    Problem F CodeForces 16E
    Problem E CodeForces 237C
    Problem C FZU 1901
    12-30
    2016-12-29
  • 原文地址:https://www.cnblogs.com/zy2009/p/7062532.html
Copyright © 2011-2022 走看看