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. Codeforces Round #207 (Div. 2)

    A:超级大水题: 代码: #include<cstdio> #define maxn 105 using namespace std; int n,a[maxn],x,y,ans; int ...

  2. Swift入门系列--Swift官方文档(2.2)--中文翻译--About Swift 关于Swift

    About Swift 关于Swift 官方文档的翻译,仅供参考,本人英语本就不好,边学边翻译,不喜勿喷. Swift is a new programming language for iOS, O ...

  3. Unity Fresnel Hero(Dota2) Shader

    Shader "HeroShader" { Properties { _Color ("Main Color", Color) = (1,1,1,1) _Rim ...

  4. HDOJ 1013题Digital Roots 大数,9余数定理

    Problem Description The digital root of a positive integer is found by summing the digits of the int ...

  5. StoryBoard 的使用

    简单入门: http://my.oschina.net/plumsoft/blog/53886 详细操作:http://www.cnblogs.com/buro79xxd/archive/2012/0 ...

  6. poj 1192最优连通子集(简单树形dp)

    题目链接:http://poj.org/problem?id=1192 #include<cstdio> #include<cstring> #include<iostr ...

  7. UILabel,文字添加下划线,中划线

    //显示下划线 //中划线 //        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber nu ...

  8. rnqoj-82-又上锁妖塔-dp

    又是一个敢想就敢做的题目... 同时记录更新两个状态 dp[i] :第i层是飞上去的 df[i]  :第i层是走上去的 dp[i]=min(df[i-1],df[i-2]); df[i]=min(dp ...

  9. 公司框架将入参Map化

    1.Map<String,Object> map = BeanUtil.describe(inDto);

  10. ng-select ng-options ng-repeat的用法与区别

    最近在用angularJS里的ng-select,ng-options,ng-repeat,发现有两点不太方便: 1.当数据复杂时,循环起来比较麻烦 2.首选项如果不设置,就会为空 整理一下它们的用法 ...