类名: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.清除给定字符串中的回车及换行符
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(, 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 > )
{
TempStr = regularExpressionsOfHTML(TempStr);
if (TempStr.Length > )
{
TempStr = TempStr.Substring(, TempStr.Length - );
}
}
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[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</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 = ; i < cbProperty.Items.Count; i++)
{
if (i != cbProperty.Items.Count - )
{
if (cbProperty.Items[i].Selected) str_property += "1,";
else str_property += "0,";
}
else
{
if (cbProperty.Items[i].Selected) str_property += "";
else str_property += "";
}
}
return str_property;
} /// <summary>
/// CheckBoxList取值
/// </summary>
/// <param name="Boxlist"></param>
/// <returns></returns>
public static string GetCheckBox(CheckBoxList Boxlist)
{
string chenkStr = "";
for (int i = ; 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 = ; i < propertyArray.Length; i++)
{
if (propertyArray[i] == "") 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 = ; i < cbList.Items.Count; i++)
{ if (selectid.IndexOf("," + cbList.Items[i].Value + ",") >= ) 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();
resp.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName));
string colHeaders = "", ls_item = "";
int i = ; //定义表对象与行对像,同时用DataSet对其值进行初始化
DataTable datatable = dataset.Tables[];
DataRow[] myRow = datatable.Select("");
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件
if (typeid == )
{
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (i = ; i < datatable.Columns.Count - ; i++)
colHeaders += datatable.Columns[i].Caption.ToString() + "\t";
colHeaders += datatable.Columns[i].Caption.ToString() + "\n";
//向HTTP输出流中写入取得的数据信息
resp.Write(colHeaders);
//逐行处理数据
foreach (DataRow row in myRow)
{
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for (i = ; i < row.ItemArray.Length - ; i++)
ls_item += row[i].ToString() + "\t";
ls_item += row[i].ToString() + "\n";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item = "";
}
}
else
{
if (typeid == )
{
//从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('\\', )).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(@"(\r\n)", RegexOptions.IgnoreCase);
public static Regex RegexFont = new Regex(@"<font color=" + "\".*?\"" + @">([\s\S]+?)</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[].ToString(), "");
} return str;
} }
}

【.NET】字符串处理类库的更多相关文章

  1. 字符串解压缩类库(zip、GZIP、QuickLz、snappy、lzf、jzlib)介绍

    1.ZIP. GZIP  计算机文件压缩算法,JDK中java.util.zip.*中实现.主要包括ZipInputStream/ ZipOutputStream.GZipInputStream/Zi ...

  2. Java学习

    第一个java程序: 用记事本创建一个文件名为HelloWorld.java文件,我的目录为D:\My Documents\Java-workspace\Test\HelloWorld.java. 打 ...

  3. 【原】dangerouslySetInnerHTML, 让React正常显示你的html代码

    昨天在弄一个让内容换行显示时,遇到一个问题,就是我有<br />的代码在页面中不换行,而是直接显示<br />,代码如下: <!DOCTYPE html> < ...

  4. 使php支持mbstring库

    多国语言并存就意味着多字节,PHP内置的字符串长度函数strlen无法正确处理中文字符串,它得到的只是字符串所占的字节数.对于GB2312的中文编码,strlen得到的值是汉字个数的2倍,而对于UTF ...

  5. 如何编译POCO

    Poco C++库是: 一系列C++类库,类似Java类库,.Net框架,Apple的Cocoa; 侧重于互联网时代的网络应用程序 使用高效的,现代的标准ANSI/ISO C++,并基于STL 高可移 ...

  6. 使用 Dotfuscator 对代码进行混淆

    Dotfuscator 简介 作为一种高级语言,c# 类库很容易被 .NET Reflector 这样的工具反编译.攻击者很容易从代码中找到数据库连接方式,加解密方法等重要信息.使用 dnspy 这样 ...

  7. csharp:汉字转带拼音声调

                                                                                      {                  ...

  8. Java基础 之一 基本知识

    Java基础 之一 基本知识 1.数据类型 Java有8种基本数据类型 int.short .long.byte.float.double.char.boolean 先说明以下单位之间的关系 1位 = ...

  9. [C#常用代码]类库中读取解决方案web.Config字符串

    对于类库里读取解决方案web.config文件里字符串的方法一.读取键值对的方法:1.添加引用using System.Configuration;2.web.Config配置节<appSett ...

随机推荐

  1. 《STL源代码剖析》---stl_hash_set.h阅读笔记

    STL仅仅规定接口和复杂度,对于详细实现不作要求.set大多以红黑树实现,但STL在标准规格之外提供了一个所谓的hash_set,以hash table实现.hash_set的接口,hash_tabl ...

  2. Repository在DDD中的应用

    Repository在DDD中的应用2014-10-09 08:55 by Jesse Liu, 98 阅读, 0 评论, 收藏, 编辑 概述 上一篇我们算是粗略的介绍了一下DDD,我们提到了实体.值 ...

  3. SVG 学习(一)

    SVG 意为可缩放矢量图形(Scalable Vector Graphics). SVG 使用 XML 格式定义图像. 什么是SVG? SVG 指可伸缩矢量图形 (Scalable Vector Gr ...

  4. 【剑指offer】的功率值

    标题叙述性说明: 实现函数double Power(double base, int exponent),求base的exponent次方.不得使用库函数.同一时候不须要考虑大数问题. 分析描写叙述: ...

  5. How to write own add-in for SSMS 2012 (Final release version)

    原文 How to write own add-in for SSMS 2012 (Final release version) Reading internet forums I have noti ...

  6. android JBOX2D粒子碰撞的实例,以达到特殊效果

    最近完成动画特效工作的一个发展.的效果,所以传统的三大动画无法满足咱们的需求啦(事实上这不是一个动画效果的议题.事实上有一点点游戏的感觉). 寻找一个粒子系统吧,发现JBox2D比較简单的能满足咱们 ...

  7. iOS基础 - UIButton - UIImageView

    封装思想:将相同的重复东西保存到方法里,不同的东西用参数代替.不相同的东西交给方法调用者,相同东西自己搞定. 一.UIButton和UIImageView的区别 1.显示图片 1> UIImag ...

  8. 在一个view类里面获取viewcontroller

    - (UIViewController *)viewController {     for (UIView* next = [selfsuperview]; next; next = next.su ...

  9. 【GitHub】在Mac上配置/使用Github

    以前一直听说过Github,但是自己一直不会用.最近不是太忙,于是想捣鼓捣鼓Github,没想到用了将近3个小时,才在Mac上配置成功. 首先简单介绍一下Git和Github 集中化的版本控制系统( ...

  10. 基于ffmpeg的C++播放器1

    基于ffmpeg的C++播放器 (1) 2011年12月份的时候发了这篇博客 http://blog.csdn.net/qq316293804/article/details/7107049 ,博文最 ...