一个非常好的C#字符串操作处理类StringHelper.cs
/// <summary>
/// 类说明:Assistant
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:http://www.sufeinet.com/thread-655-1-1.html
/// </summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions; namespace DotNet.Utilities
{
/// <summary>
/// 字符串操作类
/// 1、GetStrArray(string str, char speater, bool toLower) 把字符串按照分隔符转换成 List
/// 2、GetStrArray(string str) 把字符串转 按照, 分割 换为数据
/// 3、GetArrayStr(List list, string speater) 把 List 按照分隔符组装成 string
/// 4、GetArrayStr(List list) 得到数组列表以逗号分隔的字符串
/// 5、GetArrayValueStr(Dictionary<int, int> list)得到数组列表以逗号分隔的字符串
/// 6、DelLastComma(string str)删除最后结尾的一个逗号
/// 7、DelLastChar(string str, string strchar)删除最后结尾的指定字符后的字符
/// 8、ToSBC(string input)转全角的函数(SBC case)
/// 9、ToDBC(string input)转半角的函数(SBC case)
/// 10、GetSubStringList(string o_str, char sepeater)把字符串按照指定分隔符装成 List 去除重复
/// 11、GetCleanStyle(string StrList, string SplitString)将字符串样式转换为纯字符串
/// 12、GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error)将字符串转换为新样式
/// 13、SplitMulti(string str, string splitstr)分割字符串
/// 14、SqlSafeString(string String, bool IsDel)
/// </summary>
public class StringHelper
{
/// <summary>
/// 把字符串按照分隔符转换成 List
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="speater">分隔符</param>
/// <param name="toLower">是否转换为小写</param>
/// <returns></returns>
public static List<string> GetStrArray(string str, char speater, bool toLower)
{
List<string> list = new List<string>();
string[] ss = str.Split(speater);
foreach (string s in ss)
{
if (!string.IsNullOrEmpty(s) && s != speater.ToString())
{
string strVal = s;
if (toLower)
{
strVal = s.ToLower();
}
list.Add(strVal);
}
}
return list;
}
/// <summary>
/// 把字符串转 按照, 分割 换为数据
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] GetStrArray(string str)
{
return str.Split(new Char[] { ',' });
}
/// <summary>
/// 把 List<string> 按照分隔符组装成 string
/// </summary>
/// <param name="list"></param>
/// <param name="speater"></param>
/// <returns></returns>
public static string GetArrayStr(List<string> list, string speater)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < list.Count; i++)
{
if (i == list.Count - )
{
sb.Append(list[i]);
}
else
{
sb.Append(list[i]);
sb.Append(speater);
}
}
return sb.ToString();
}
/// <summary>
/// 得到数组列表以逗号分隔的字符串
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string GetArrayStr(List<int> list)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < list.Count; i++)
{
if (i == list.Count - )
{
sb.Append(list[i].ToString());
}
else
{
sb.Append(list[i]);
sb.Append(",");
}
}
return sb.ToString();
}
/// <summary>
/// 得到数组列表以逗号分隔的字符串
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string GetArrayValueStr(Dictionary<int, int> list)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<int, int> kvp in list)
{
sb.Append(kvp.Value + ",");
}
if (list.Count > )
{
return DelLastComma(sb.ToString());
}
else
{
return "";
}
} #region 删除最后一个字符之后的字符 /// <summary>
/// 删除最后结尾的一个逗号
/// </summary>
public static string DelLastComma(string str)
{
return str.Substring(, str.LastIndexOf(","));
} /// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(string str, string strchar)
{
return str.Substring(, str.LastIndexOf(strchar));
} #endregion /// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ToSBC(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = ; i < c.Length; i++)
{
if (c[i] == )
{
c[i] = (char);
continue;
}
if (c[i] < )
c[i] = (char)(c[i] + );
}
return new string(c);
} /// <summary>
/// 转半角的函数(SBC case)
/// </summary>
/// <param name="input">输入</param>
/// <returns></returns>
public static string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = ; i < c.Length; i++)
{
if (c[i] == )
{
c[i] = (char);
continue;
}
if (c[i] > && c[i] < )
c[i] = (char)(c[i] - );
}
return new string(c);
} /// <summary>
/// 把字符串按照指定分隔符装成 List 去除重复
/// </summary>
/// <param name="o_str"></param>
/// <param name="sepeater"></param>
/// <returns></returns>
public static List<string> GetSubStringList(string o_str, char sepeater)
{
List<string> list = new List<string>();
string[] ss = o_str.Split(sepeater);
foreach (string s in ss)
{
if (!string.IsNullOrEmpty(s) && s != sepeater.ToString())
{
list.Add(s);
}
}
return list;
} #region 将字符串样式转换为纯字符串
/// <summary>
/// 将字符串样式转换为纯字符串
/// </summary>
/// <param name="StrList"></param>
/// <param name="SplitString"></param>
/// <returns></returns>
public static string GetCleanStyle(string StrList, string SplitString)
{
string RetrunValue = "";
//如果为空,返回空值
if (StrList == null)
{
RetrunValue = "";
}
else
{
//返回去掉分隔符
string NewString = "";
NewString = StrList.Replace(SplitString, "");
RetrunValue = NewString;
}
return RetrunValue;
}
#endregion #region 将字符串转换为新样式
/// <summary>
/// 将字符串转换为新样式
/// </summary>
/// <param name="StrList"></param>
/// <param name="NewStyle"></param>
/// <param name="SplitString"></param>
/// <param name="Error"></param>
/// <returns></returns>
public static string GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error)
{
string ReturnValue = "";
//如果输入空值,返回空,并给出错误提示
if (StrList == null)
{
ReturnValue = "";
Error = "请输入需要划分格式的字符串";
}
else
{
//检查传入的字符串长度和样式是否匹配,如果不匹配,则说明使用错误。给出错误信息并返回空值
int strListLength = StrList.Length;
int NewStyleLength = GetCleanStyle(NewStyle, SplitString).Length;
if (strListLength != NewStyleLength)
{
ReturnValue = "";
Error = "样式格式的长度与输入的字符长度不符,请重新输入";
}
else
{
//检查新样式中分隔符的位置
string Lengstr = "";
for (int i = ; i < NewStyle.Length; i++)
{
if (NewStyle.Substring(i, ) == SplitString)
{
Lengstr = Lengstr + "," + i;
}
}
if (Lengstr != "")
{
Lengstr = Lengstr.Substring();
}
//将分隔符放在新样式中的位置
string[] str = Lengstr.Split(',');
foreach (string bb in str)
{
StrList = StrList.Insert(int.Parse(bb), SplitString);
}
//给出最后的结果
ReturnValue = StrList;
//因为是正常的输出,没有错误
Error = "";
}
}
return ReturnValue;
}
#endregion /// <summary>
/// 分割字符串
/// </summary>
/// <param name="str"></param>
/// <param name="splitstr"></param>
/// <returns></returns>
public static string[] SplitMulti(string str, string splitstr)
{
string[] strArray = null;
if ((str != null) && (str != ""))
{
strArray = new Regex(splitstr).Split(str);
}
return strArray;
}
public static string SqlSafeString(string String, bool IsDel)
{
if (IsDel)
{
String = String.Replace("'", "");
String = String.Replace("\"", "");
return String;
}
String = String.Replace("'", "'");
String = String.Replace("\"", """);
return String;
} #region 获取正确的Id,如果不是正整数,返回0
/// <summary>
/// 获取正确的Id,如果不是正整数,返回0
/// </summary>
/// <param name="_value"></param>
/// <returns>返回正确的整数ID,失败返回0</returns>
public static int StrToId(string _value)
{
if (IsNumberId(_value))
return int.Parse(_value);
else
return ;
}
#endregion
#region 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。
/// <summary>
/// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外)
/// </summary>
/// <param name="_value">需验证的字符串。。</param>
/// <returns>是否合法的bool值。</returns>
public static bool IsNumberId(string _value)
{
return QuickValidate("^[1-9]*[0-9]*$", _value);
}
#endregion
#region 快速验证一个字符串是否符合指定的正则表达式。
/// <summary>
/// 快速验证一个字符串是否符合指定的正则表达式。
/// </summary>
/// <param name="_express">正则表达式的内容。</param>
/// <param name="_value">需验证的字符串。</param>
/// <returns>是否合法的bool值。</returns>
public static bool QuickValidate(string _express, string _value)
{
if (_value == null) return false;
Regex myRegex = new Regex(_express);
if (_value.Length == )
{
return false;
}
return myRegex.IsMatch(_value);
}
#endregion #region 根据配置对指定字符串进行 MD5 加密
/// <summary>
/// 根据配置对指定字符串进行 MD5 加密
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string GetMD5(string s)
{
//md5加密
s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString(); return s.ToLower().Substring(, );
}
#endregion #region 得到字符串长度,一个汉字长度为2
/// <summary>
/// 得到字符串长度,一个汉字长度为2
/// </summary>
/// <param name="inputString">参数字符串</param>
/// <returns></returns>
public static int StrLength(string inputString)
{
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = ;
byte[] s = ascii.GetBytes(inputString);
for (int i = ; i < s.Length; i++)
{
if ((int)s[i] == )
tempLen += ;
else
tempLen += ;
}
return tempLen;
}
#endregion #region 截取指定长度字符串
/// <summary>
/// 截取指定长度字符串
/// </summary>
/// <param name="inputString">要处理的字符串</param>
/// <param name="len">指定长度</param>
/// <returns>返回处理后的字符串</returns>
public static string ClipString(string inputString, int len)
{
bool isShowFix = false;
if (len % == )
{
isShowFix = true;
len--;
}
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = ;
string tempString = "";
byte[] s = ascii.GetBytes(inputString);
for (int i = ; i < s.Length; i++)
{
if ((int)s[i] == )
tempLen += ;
else
tempLen += ; try
{
tempString += inputString.Substring(i, );
}
catch
{
break;
} if (tempLen > len)
break;
} byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
if (isShowFix && mybyte.Length > len)
tempString += "…";
return tempString;
}
#endregion #region HTML转行成TEXT
/// <summary>
/// HTML转行成TEXT
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string HtmlToTxt(string strHtml)
{
string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
@"([\r\n])[\s]+",
@"&(quot|#34);",
@"&(amp|#38);",
@"&(lt|#60);",
@"&(gt|#62);",
@"&(nbsp|#160);",
@"&(iexcl|#161);",
@"&(cent|#162);",
@"&(pound|#163);",
@"&(copy|#169);",
@"&#(\d+);",
@"-->",
@"<!--.*\n"
}; string newReg = aryReg[];
string strOutput = strHtml;
for (int i = ; i < aryReg.Length; i++)
{
Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, string.Empty);
} strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput.Replace("\r\n", ""); return strOutput;
}
#endregion #region 判断对象是否为空
/// <summary>
/// 判断对象是否为空,为空返回true
/// </summary>
/// <typeparam name="T">要验证的对象的类型</typeparam>
/// <param name="data">要验证的对象</param>
public static bool IsNullOrEmpty<T>(T data)
{
//如果为null
if (data == null)
{
return true;
} //如果为""
if (data.GetType() == typeof(String))
{
if (string.IsNullOrEmpty(data.ToString().Trim()))
{
return true;
}
} //如果为DBNull
if (data.GetType() == typeof(DBNull))
{
return true;
} //不为空
return false;
} /// <summary>
/// 判断对象是否为空,为空返回true
/// </summary>
/// <param name="data">要验证的对象</param>
public static bool IsNullOrEmpty(object data)
{
//如果为null
if (data == null)
{
return true;
} //如果为""
if (data.GetType() == typeof(String))
{
if (string.IsNullOrEmpty(data.ToString().Trim()))
{
return true;
}
} //如果为DBNull
if (data.GetType() == typeof(DBNull))
{
return true;
} //不为空
return false;
}
#endregion
}
}
一个非常好的C#字符串操作处理类StringHelper.cs的更多相关文章
- 一个封装好的CSV文件操作C#类代码
using System.Data; using System.IO; namespace DotNet.Utilities { /// <summary> /// CSV文件转换类 // ...
- C语言字符串操作总结大全(超具体)
1)字符串操作 strcpy(p, p1) 复制字符串 strncpy(p, p1, n) 复制指定长度字符串 strcat(p, p1) 附加字符串 strncat(p, p1, n) 附加指定长度 ...
- 【转载】微软官方提供的Sqlserver数据库操作帮助类SQLHelper类
在.NET平台中,C#语言一般使用ADO.NET组件来操作Sqlserver数据库,通过ADO.NET组件可以实现连接数据库.查询数据集.执行SQL语句以及关闭数据库连接等操作,为此网上有很多开发者自 ...
- 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法
1.利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法 首先判断字符串的长度是否为0,如果是,直接返回字符串 第二,循环判断字符串的首部是否有空格,如 ...
- python练习题:利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法
方法一: # -*- coding: utf-8 -*- # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法: def trim(s): whil ...
- python学习笔记(字符串操作、字典操作、三级菜单实例)
字符串操作 name = "alex" print(name.capitalize()) #首字母大写 name = "my name is alex" pri ...
- php字符串操作集锦
web操作, 主要就是对字符文本信息进行处理, 所以, 字符串操作几乎占了很大一部分的php操作.包括 注意strstr 和 strtr的区别? 前者表示字符串查找返回字符串,后者表示字符串中字符替换 ...
- java 字符串操作和日期操作
一.字符串操作 创建字符串 String s2 = new String("Hello World"); String s1 = "Hello World"; ...
- [No000078]Python3 字符串操作
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Python 字符串操作 string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分 ...
随机推荐
- keras系列︱迁移学习:利用InceptionV3进行fine-tuning及预测、完美案例(五)
引自:http://blog.csdn.net/sinat_26917383/article/details/72982230 之前在博客<keras系列︱图像多分类训练与利用bottlenec ...
- MATLAB实现多元线性回归预测
一.简单的多元线性回归: data.txt ,230.1,37.8,69.2,22.1 ,44.5,39.3,45.1,10.4 ,17.2,45.9,69.3,9.3 ,151.5,41.3,58. ...
- Java堆外内存管理
Java堆外内存管理 1.JVM可以使用的内存分外2种:堆内存和堆外内存: 堆内存完全由JVM负责分配和释放,如果程序没有缺陷代码导致内存泄露,那么就不会遇到java.lang.OutOfMemo ...
- Rsync命令参数详解
在对rsync服务器配置结束以后,下一步就需要在客户端发出rsync命令来实现将服务器端的文件备份到客户端来.rsync是一个功能非常强大的工具,其命令也有很多功能特色选项,我们下面就对它的选项一一进 ...
- Python基础知识小结
1. 关于函数传参 def func(n, *args, **kwargs): print n print args print kwargs if __name__ == '__main__': # ...
- 【C】——如何用线程进行参数的传递
直接上代码: #include<pthread.h> #include<stdio.h> struct val{ int num1; int num2; }; //send a ...
- java操作大文件复制
https://www.cnblogs.com/coprince/p/6594348.html https://blog.csdn.net/w592376568/article/details/796 ...
- Spring Cloud Config 配置中心 生产环境下相关问题
参照以前写的博客进行搭建配置中心集群 1.如果要使用 服务器端自动刷新,所有客户端同步功能.要先安装RabbitMQ 2.如果要使用自动加解密功能,要先安装JAVA JCE扩展.
- eclipse中设置字体为VC经典字体Fixedsys
- jquery 实现下拉菜单
Jquery 是一个轻量的框架,个人认为非常好用,今天就写一个非常简单的例子,实现下拉菜单功能: 首先肯定要在页面引用jquery.js 版本不限 : 接下来把=================== ...