• 【.NET】字符串处理


    类名:DealString

    /// 1.截取字符串,最后加3个小数点
    /// 2.获得指定Url的参数的string类型值
    /// 3.判断数据类型
    /// 4.过滤JS标记
    /// 5.获取CheckBoxList属性值
    /// 6.通过ID绑定CheckBoxList选项
    /// 7.CheckBoxList取值
    /// 8.设置CheckBoxList属性值
    /// 9.通过ID绑定CheckBoxList选项
    /// 10.得到按指定CheckBoxList选项字符串
    /// 11.生成Execl
    /// 12.获得当前绝对路径
    /// 13.得到正则编译参数设置
    /// 14.清除给定字符串中的回车及换行符
    /// 15.分页方法
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Text.RegularExpressions;
    
    
    namespace Tools
    {
        /// <summary>
        /// DealString 的摘要说明。
        /// </summary>
        public class DealString
        {
    
            /// <summary>
            /// 截取字符串
            /// </summary>
            /// <param name="obj"></param>
            /// <param name="count"></param>
            /// <returns></returns>
            public static string substring(object obj, int count)
            {
                string str = tostring(obj);
                if (str.Length > count)
                {
                    str = obj.ToString().Substring(0, count) + "...";
                }
                return str;
    
            }
    
            /// <summary>
            /// 获得指定Url参数的string类型值
            /// </summary>
            /// <param name="strName">Url参数</param>
            /// <param name="defValue">缺省值</param>
            /// <returns>Url参数的string类型值</returns>
            public static string GetQueryString(string strName)
            {
                string GetQueryString = (HttpContext.Current.Request.QueryString[strName]);
                return GetQueryString;
            }
    
            public static string tostring(object obj)
            {
                string result = "";
                if (obj != null)
                {
                    result = obj.ToString().Trim();
                }
                return result;
            }
    
            /// <summary>
            /// 过滤html标签
            /// </summary>
            /// <param name="TempStr"></param>
            /// <returns></returns>
            public static string StripHTML(string TempStr)
            {
                if (TempStr != null)
                {
                    if (TempStr.Length > 0)
                    {
                        TempStr = regularExpressionsOfHTML(TempStr);
                        if (TempStr.Length > 0)
                        {
                            TempStr = TempStr.Substring(0, TempStr.Length - 1);
                        }
                    }
                    TempStr = TempStr.Replace("&nbsp;", "");
                }
                return TempStr;
            }
            public static string regularExpressionsOfHTML(string TempContent)
            {
                //TempContent = System.Text.RegularExpressions.Regex.Replace(TempContent,"<[^>]+>",""); //任意多个
                TempContent = System.Text.RegularExpressions.Regex.Replace(TempContent, "<[^>]*>", ""); //匹配一个
                return TempContent.Trim();
    
            }
            /// <summary>
            /// 判断数据类型
            /// </summary>
            /// <param name="strNumber)"></param>
            /// <returns></returns>    
            public bool IsNumber(String strNumber)
            {
                Regex objNotNumberPattern = new Regex("[^0-9.-]");
                Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
                Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
                String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
                String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
                Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
    
                return !objNotNumberPattern.IsMatch(strNumber) &&
                !objTwoDotPattern.IsMatch(strNumber) &&
                !objTwoMinusPattern.IsMatch(strNumber) &&
                objNumberPattern.IsMatch(strNumber);
            }
    
            public static bool IsNumeric(string value)
            {
                return Regex.IsMatch(value, @"^[+-]?d*[.]?d*$");
            }
            public static bool IsInt(string value)
            {
                return Regex.IsMatch(value, @"^[+-]?d*$");
            }
            public static bool IsUnsign(string value)
            {
                return Regex.IsMatch(value, @"^d*[.]?d*$");
            }
    
            /// <summary>
            /// 过滤JS标记
            /// </summary>
            /// <param name="html"></param>
            /// <returns></returns>
            public string wipeScript(string html)
            {
                System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[sS]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[sS]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[sS]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[sS]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[sS]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                html = regex1.Replace(html, ""); //过滤<script></script>标记
                html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
                html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
                html = regex4.Replace(html, ""); //过滤iframe
                html = regex5.Replace(html, ""); //过滤frameset
                return html;
            }
    
            /// <summary>
            /// 获取CheckBoxList属性值
            /// </summary>
            /// <param name="cbProperty">CheckBoxList对象</param>
            /// <returns></returns>
            public static string GetPropertyValue(CheckBoxList cbProperty)
            {
                string str_property = "";
                for (int i = 0; i < cbProperty.Items.Count; i++)
                {
                    if (i != cbProperty.Items.Count - 1)
                    {
                        if (cbProperty.Items[i].Selected) str_property += "1,";
                        else str_property += "0,";
                    }
                    else
                    {
                        if (cbProperty.Items[i].Selected) str_property += "1";
                        else str_property += "0";
                    }
                }
                return str_property;
            }
    
    
            /// <summary>
            /// CheckBoxList取值
            /// </summary>
            /// <param name="Boxlist"></param>
            /// <returns></returns>
            public static string GetCheckBox(CheckBoxList Boxlist)
            {
                string chenkStr = "";
                for (int i = 0; i < Boxlist.Items.Count; i++)
                {
                    if (Boxlist.Items[i].Selected == true)
                    {
                        chenkStr += Boxlist.Items[i].Value + ",";
                    }
                }
                return chenkStr;
            }
    
            /// <summary>
            /// 设置CheckBoxList属性值
            /// </summary>
            /// <param name="cbProperty">CheckBoxList对象</param>
            /// <param name="propertyvalue">属性值</param>
            public static void SetPropertyValue(CheckBoxList cbProperty, string propertyvalue)
            {
                string[] propertyArray = propertyvalue.Split(',');
                for (int i = 0; i < propertyArray.Length; i++)
                {
                    if (propertyArray[i] == "1") cbProperty.Items[i].Selected = true;
                }
    
            }
            /// <summary>
            /// 通过ID绑定CheckBoxList选项
            /// </summary>
            /// <param name="cbList">CheckBoxList对象</param>
            /// <param name="selectid">批定ID</param>
            public static void SetSelectByID(CheckBoxList cbList, string selectid)
            {
                selectid = "," + selectid + ",";
    
                for (int i = 0; i < cbList.Items.Count; i++)
                {
    
                    if (selectid.IndexOf("," + cbList.Items[i].Value + ",") >= 0) cbList.Items[i].Selected = true;
    
                }
            }
            /// <summary>
    
            /// 得到按指定CheckBoxList选项字符串
            /// </summary>
            /// <param name="cbList">CheckBoxList对象</param>
            /// <returns></returns>
            public static string GetSelectString(CheckBoxList cbList)
            {
                string result = "";
                foreach (ListItem item in cbList.Items)
                {
                    if (item.Selected) result += item.Value + ",";
                }
                return result.TrimEnd(new char[] { ',' });
            }
    
            /// <summary>
            /// 生成Execl
            /// </summary>
            /// <param name="dataset">要生成的数据</param>
            /// <param name="typeid">1生成Execl、2直接把数据写入XML</param>
            /// <param name="FileName">文件名</param>
            /// <param name="page">当前页面类</param>
            public static void CreateExcel(DataSet dataset, int typeid, string FileName, System.Web.UI.Page page)
            {
                HttpResponse resp;
                resp = page.Response;
                resp.ContentEncoding = System.Text.Encoding.GetEncoding(0);
                resp.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName));
                string colHeaders = "", ls_item = "";
                int i = 0;
    
                //定义表对象与行对像,同时用DataSet对其值进行初始化 
                DataTable datatable = dataset.Tables[0];
                DataRow[] myRow = datatable.Select("");
                // typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件 
                if (typeid == 1)
                {
                    //取得数据表各列标题,各标题之间以	分割,最后一个列标题后加回车符 
                    for (i = 0; i < datatable.Columns.Count - 1; i++)
                        colHeaders += datatable.Columns[i].Caption.ToString() + "	";
                    colHeaders += datatable.Columns[i].Caption.ToString() + "
    ";
                    //向HTTP输出流中写入取得的数据信息 
                    resp.Write(colHeaders);
                    //逐行处理数据 
                    foreach (DataRow row in myRow)
                    {
                        //在当前行中,逐列获得数据,数据之间以	分割,结束时加回车符
     
                        for (i = 0; i < row.ItemArray.Length - 1; i++)
                            ls_item += row[i].ToString() + "	";
                        ls_item += row[i].ToString() + "
    ";
                        //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 
                        resp.Write(ls_item);
                        ls_item = "";
                    }
                }
                else
                {
                    if (typeid == 2)
                    {
                        //从DataSet中直接导出XML数据并且写到HTTP输出流中 
                        resp.Write(dataset.GetXml());
                    }
                }
                //写缓冲区中的数据到HTTP头文件中 
                resp.End();
            }
    
            /// <summary>
            /// 获得当前绝对路径
            /// </summary>
            /// <param name="strPath">指定的路径</param>
            /// <returns>绝对路径</returns>
            public static string GetMapPath(string strPath)
            {
                if (HttpContext.Current != null)
                {
                    return HttpContext.Current.Server.MapPath(strPath);
                }
                else //非web程序引用
                {
                    strPath = strPath.Replace("/", "\");
                    if (strPath.StartsWith("\"))
                    {
                        strPath = strPath.Substring(strPath.IndexOf('\', 1)).TrimStart('\');
                    }
                    return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
                }
            }
    
    
            /// <summary>
            /// 得到正则编译参数设置
            /// </summary>
            /// <returns>参数设置</returns>
            public static RegexOptions GetRegexCompiledOptions()
            {
    #if NET1
                return RegexOptions.Compiled;
    #else
                return RegexOptions.None;
    #endif
            }
    
    
            /// <summary>
            /// 清除给定字符串中的回车及换行符
            /// </summary>
            /// <param name="str">要清除的字符串</param>
            /// <returns>清除后返回的字符串</returns>
    
            private static Regex RegexBr = new Regex(@"(
    )", RegexOptions.IgnoreCase);
            public static Regex RegexFont = new Regex(@"<font color=" + "".*?"" + @">([sS]+?)</font>", GetRegexCompiledOptions());
            public static string ClearBR(string str)
            {
                Match m = null;
    
                for (m = RegexBr.Match(str); m.Success; m = m.NextMatch())
                {
                    str = str.Replace(m.Groups[0].ToString(), "");
                }
    
                return str;
            }
    
        }
    }
  • 相关阅读:
    Web前端面试(二):CSS盒模型
    Web前端面试题
    微信小程序之base64图片如何预览与一键保存到本地相册?
    微信小程序 —搜索框
    初次
    用document.getElementsByTagName()返回的真的是数组吗?
    《精通CSS:高级Web标准解决方案》学习笔记(下)
    Git常用命令
    博客施工暂时告一段落
    《精通CSS:高级Web标准解决方案》学习笔记(上)
  • 原文地址:https://www.cnblogs.com/chencsblog/p/3289036.html
Copyright © 2020-2023  润新知