public class StringHelper
    {
        /// <summary>
        /// 截字符串
        /// </summary>
        /// <param name="sInString">字符串</param>
        /// <param name="iCutLength">截几个字</param>
        /// <returns>截好的字符串</returns>
        public static string CutStr(object sInStrings, int iCutLength)
        {

string sInString = sInStrings.ToString();
            if (sInString == null || sInString.Length == 0 || iCutLength <= 0) return "";
            int iCount = System.Text.Encoding.Default.GetByteCount(sInString);
            if (iCount > iCutLength)
            {
                int iLength = 0;
                for (int i = 0; i < sInString.Length; i++)
                {
                    int iCharLength = System.Text.Encoding.Default.GetByteCount(new char[] { sInString[i] });
                    iLength += iCharLength;
                    if (iLength == iCutLength)
                    //需要截取的和总字符串位数相等
                    {
                        sInString = sInString.Substring(0, i + 1);
                        break;
                    }
                    else if (iLength > iCutLength)//需要截取的小于总字符长度
                    {
                        sInString = sInString.Substring(0, i) + "...";//。。。
                        break;
                    }
                }
            }
            return sInString;
        }

/// <summary>
        /// 按字节长度截取字符串(支持截取带HTML代码样式的字符串)
        /// </summary>
        /// <param name=”param”>将要截取的字符串参数</param>
        /// <param name=”length”>截取的字节长度</param>
        /// <param name=”end”>字符串末尾补上的字符串</param>此处写死了,可放开
        /// <returns>返回截取后的字符串</returns>
        public static string SubstringToHTML(string param, int length)
        {
            string end = "...";
            string Pattern = null;
            MatchCollection m = null;
            StringBuilder result = new StringBuilder();
            int n = 0;
            char temp;
            bool isCode = false; //是不是HTML代码
            bool isHTML = false; //是不是HTML特殊字符,如&nbsp;
            char[] pchar = param.ToCharArray();
            for (int i = 0; i < pchar.Length; i++)
            {
                temp = pchar[i];
                if (temp == '<')
                {
                    isCode = true;
                }
                else if (temp == '&')
                {
                    isHTML = true;
                }
                else if (temp == '>' && isCode)
                {
                    n -= 1;
                    isCode = false;
                }
                else if (temp == ';' && isHTML)
                {
                    isHTML = false;
                }

if (!isCode && !isHTML)
                {
                    n = n + 1;
                    //UNICODE码字符占两个字节
                    if (System.Text.Encoding.Default.GetBytes(temp + "").Length > 1)
                    {
                        n = n + 1;
                    }
                }

result.Append(temp);
                if (n >= length)
                {
                    break;
                }
            }
            result.Append(end);
            //取出截取字符串中的HTML标记
            string temp_result = result.ToString().Replace("(>)[^<>]*(<?)", "$1$2");
            //去掉不需要结素标记的HTML标记
            temp_result = temp_result.Replace(@"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML

|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD

|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta

|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
             "");
            //去掉成对的HTML标记
            temp_result = temp_result.Replace(@"<([a-zA-Z]+)[^<>]*>(.*?)</1>", "$2");
            //用正则表达式取出标记
            Pattern = ("<([a-zA-Z]+)[^<>]*>");
            m = Regex.Matches(temp_result, Pattern);
            ArrayList endHTML = new ArrayList();
            foreach (Match mt in m)
            {
                endHTML.Add(mt.Result("$1"));
            }
            //补全不成对的HTML标记
            for (int i = endHTML.Count - 1; i >= 0; i--)
            {
                result.Append("</");
                result.Append(endHTML[i]);
                result.Append(">");
            }
            return result.ToString();
        }

}
}

StringHelper类,内容截取,特别适合资讯展示列表的更多相关文章

  1. 【黑马Android】(04)数据库的创建和sql语句增删改查/LinearLayout展示列表数据/ListView的使用和BaseAdater/内容提供者创建

    数据库的创建和sql语句增删改查 1. 载入驱动. 2. 连接数据库. 3. 操作数据库. 创建表: create table person( _id integer primary key, nam ...

  2. ***Redis hash是一个string类型的field和value的映射表.它的添加、删除操作都是O(1)(平均)。hash特别适合用于存储对象

    http://redis.readthedocs.org/en/latest/hash/hset.html HSET HSET key field value   (存一个对象的时候key存) 将哈希 ...

  3. 开源:矿Android新闻client,快、小、支持离线阅读、操作简单、内容丰富,形式多样展示、的信息量、全功能 等待(离开码邮箱)

    分享:矿Android新闻client.快.小.支持离线阅读.操作简单.内容丰富,形式多样展示.的信息量.全功能 等待(离开码邮箱) 历时30天我为了开发这个新闻clientAPP,下面简称觅闻 ht ...

  4. javascript 如何打印、输出数组内容(将数组内容以字符串的形式展示出来)

        1.情景展示 在实际开发过程中,为了调试,有时我们需要看数组中具体包含了哪些数据,但是, 如果我们直接打印该数组对象,显示的结果却不是我们想要的. 如何才能将数组内容打印出来呢?(将数组内容以 ...

  5. 使用Bootstrap 3开发响应式网站实践05,使用Tab、Modal、Form展示内容,使用Popover、Tooltip展示提示信息

    本篇体验用Tab插件显示内容.Html部分为: <div class="row" id="moreInfo"> <div class=&quo ...

  6. React入门 (2)—实现微博展示列表

    前言 如果从来不了解React先看前篇React入门 (1)-使用指南(包括ES5和ES6对比). 本文为了能将前篇学到的react知识学以致用,做了一个类似微博展示列表的demo.使用的是ES6+R ...

  7. 微信小程序信息展示列表

    微信小程序信息展示列表 效果展示: 代码展示: wxml <view class="head"> <view class="head_item" ...

  8. crm --- 1.admin , 展示列表 和 分页

    一.admin (创建超级用户) 1.注册: 1.创建一个超级管理员,使用如下命令: python manage.py createsuperuser 2.输入打算使用的登录名: username:m ...

  9. Python3执行DOS命令并截取其输出到一个列表字符串,同时写入一个文件

    #执行DOS命令并截取其输出到一个列表字符串,同时写入一个文件#这个功能很有用listing=os.popen('ipconfig').readlines()for i in listing: pri ...

随机推荐

  1. Initializing Spring root WebApplicationContext

    最近 我部署ssh项目的时候经常出现这样的问题,我的解决办法是 log4j:WARN No appenders could be found for logger (org.springframewo ...

  2. lc面试准备:Number of 1 Bits

    1 题目 Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also ...

  3. SD卡中FAT32文件格式快速入门(图文详细介绍)

    说明: MBR :Master Boot Record ( 主引导记录) DBR :DOS Boot Record ( 引导扇区) FAT :File Allocation Table ( 文件分配表 ...

  4. Hibernate(九)一对多双向关联映射

    上次的博文Hibernate从入门到精通(八)一对多单向关联映射中,我们讲解了一下一对多单向映射的相关 内容,这次我们讲解一下一对多双向映射的相关内容. 一对多双向关联映射 一对多双向关联映 射,即在 ...

  5. HDU-1300(基础方程DP-遍历之前所有状态)

    Problem Description In Pearlania everybody is fond of pearls. One company, called The Royal Pearl, p ...

  6. git submodule的操作

    对于有submodule的库,检出的方法是: git clone https://github.com/BelledonneCommunications/linphone-android.git -- ...

  7. 杭州(含嘉兴,绍兴,金华,湖州,义乌)Uber优步司机奖励政策(1月25日~1月31日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  8. flexpaper 背景色变化

    1.mxml文件头部:添加 backgroundAlpha="0" <s:Application xmlns:fx="http://ns.adobe.com/mxm ...

  9. JSP路径的问题

    JSP因为是客户端使用的路径,所以完全可以使用全路径形式 那么在JSP里面使用路径的方式有两种,超链接或者form 当我们在MyEclipse中新建JSP时,可以发现有下面 <%@ page l ...

  10. AIX操作oracle

    oracle:出现下述错误,无法连接用户. ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist ...