C# 字符串处理类
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ZD.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 = 0; i < list.Count; i++)
{
if (i == list.Count - 1)
{
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 = 0; i < list.Count; i++)
{
if (i == list.Count - 1)
{
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 > 0)
{
return DelLastComma(sb.ToString());
}
else
{
return "";
}
}
#region 删除最后一个字符之后的字符
/// <summary>
/// 删除最后结尾的一个逗号
/// </summary>
public static string DelLastComma(string str)
{
return str.Substring(0, str.LastIndexOf(","));
}
/// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(string str, string strchar)
{
return str.Substring(0, 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 = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
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 = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
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 = 0; i < NewStyle.Length; i++)
{
if (NewStyle.Substring(i, 1) == SplitString)
{
Lengstr = Lengstr + "," + i;
}
}
if (Lengstr != "")
{
Lengstr = Lengstr.Substring(1);
}
//将分隔符放在新样式中的位置
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 0;
}
#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 == 0)
{
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(8, 16);
}
#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 = 0;
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
tempLen += 2;
else
tempLen += 1;
}
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 % 2 == 1)
{
isShowFix = true;
len--;
}
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = 0;
string tempString = "";
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
tempLen += 2;
else
tempLen += 1;
try
{
tempString += inputString.Substring(i, 1);
}
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[0];
string strOutput = strHtml;
for (int i = 0; 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# 字符串处理类的更多相关文章
- python 使用字符串名调用类以及调用类方法名
在python中,有时调用者仅知道类名和类方法,不负责实际的函数调用,而是将要调用的类名和类方法告诉一个中间函数,由中间函数负责实际调用函数.中间函数需以被告知的字符串调用类和类方法. ...
- Swift微博项目--Swift中通过类名字符串创建类以及动态加载控制器的实现
Swift中用类名字符串创建类(用到了命名空间) OC中可以直接通过类名的字符串转换成对应的类来操作,但是Swift中必须用到命名空间,也就是说Swift中通过字符串获取类的方式为NSClassFro ...
- php byte数组与字符串转换类
<?php /** * byte数组与字符串转化类 * @author ZT */ class Bytes { /** * 转换一个string字符串为byte数组 * @param $str ...
- php截取指定字符串之间的字符串的类
一个php截取指定字符串之间的字符串的类 <?php class get_c_str { var $str; var $start_str; var $end_str; va ...
- StringUtils 字符串工具类
package com.thinkgem.jeesite.common.utils; import java.io.File; import java.io.IOException; import j ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
- 也谈C#之Json,从Json字符串到类代码
原文:也谈C#之Json,从Json字符串到类代码 阅读目录 json转类对象 逆思考 从json字符串自动生成C#类 json转类对象 自从.net 4.0开始,微软提供了一整套的针对json进 ...
- * 类描写叙述:字符串工具类 类名称:String_U
/****************************************** * 类描写叙述:字符串工具类 类名称:String_U * ************************** ...
- bjective-C 中核心处理字符串的类是 NSString 与 NSMutableString
Objective-C 中核心处理字符串的类是 NSString 与 NSMutableString ,这两个类最大的区别就是NSString 创建赋值以后该字符串的内容与长度不能在动态的更改,除非重 ...
- [Java初探04]__字符串(String类)相关
前言 接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面 ...
随机推荐
- C++ format 函数
转载原文链接:https://blog.csdn.net/nowhaha/article/details/38710571 原博主很有心,文字标有颜色,奥利给! Thanks C++ format ...
- Thymeleaf 异常:Exception processing template "index": An error happened during template parsing (template: "class path resource [templates/index.html]")
Spring Boot 项目,在 Spring Tool Suite 4, Version: 4.4.0.RELEASE 运行没有问题,将项目中的静态资源和页面复制到 IDEA 的项目中,除了 IDE ...
- 可能是东半球第二好用的软件工具全部在这里(update in 2020.10.09)
1. 产品经理工具种草 浏览器:Google Chrome 网络浏览器 原型绘制软件:墨刀- 在线产品原型设计与协作平台(https://modao.cc/).摹客mockplus - 摹客,让设计和 ...
- TP5调用小程序微信支付,回调,在待支付中再次调用微信支付
1,必须要有 $mch_id $key $appid这三个值,是需要去申请的,我是直接用公司的2,购买商品订单号用户openid统一下单名称商品价格(必须以分为单位,调起微信支付)服务器的ip地址(没 ...
- python之线程了解部分
一.死锁(了解) 死锁产生的4个必要条件: 互斥:一个资源同一时刻只允许一个线程进行访问 占有未释放:一个线程占有资源,且没有释放资源 不可抢占:一个已经占有资源的线程无法抢占到其他线程拥有的资源 循 ...
- golang 进行grpc调用
参考https://blog.csdn.net/qq_32744005/article/details/105606383 go get google.golang.org/grpc go get - ...
- python简单实现论文查重(软工第一次项目作业)
前言 软件工程 https://edu.cnblogs.com/campus/gdgy/informationsecurity1812 作业要求 https://edu.cnblogs.com/cam ...
- 解决SpringBoot 定时计划 quartz job 任务重复执行多次(10次)
上一篇:SpringBoot多任务Quartz动态管理Scheduler,时间配置,页面+源 设置了多个 任务,本应该是各司其职的,任务调用多线程处理任务,but这个定时任务竟然同时跑了10次???如 ...
- 本溪6397.7539(薇)xiaojie:本溪哪里有xiaomei
本溪哪里有小姐服务大保健[微信:6397.7539倩儿小妹[本溪叫小姐服务√o服务微信:6397.7539倩儿小妹[本溪叫小姐服务][十微信:6397.7539倩儿小妹][本溪叫小姐包夜服务][十微信 ...
- 编程福利:50本C语言电子书,你还怕没书看吗!
推荐适合编程新手入门的几本经典的C语言书籍. 1.<C程序设计语言> C语言之父的著作,被称为C语言的的圣经.全球最经典的C语言教程.这本书最大的特点是精炼.读起来不会觉得"啰嗦 ...