一个非常好的C#字符串操作处理类StringHelper.cs
1 /// <summary> 2 /// 类说明:Assistant 3 /// 编 码 人:苏飞 4 /// 联系方式:361983679 5 /// 更新网站:http://www.sufeinet.com/thread-655-1-1.html 6 /// </summary> 7 using System; 8 using System.Collections.Generic; 9 using System.Text; 10 using System.Text.RegularExpressions; 11 12 namespace DotNet.Utilities 13 { 14 /// <summary> 15 /// 字符串操作类 16 /// 1、GetStrArray(string str, char speater, bool toLower) 把字符串按照分隔符转换成 List 17 /// 2、GetStrArray(string str) 把字符串转 按照, 分割 换为数据 18 /// 3、GetArrayStr(List list, string speater) 把 List 按照分隔符组装成 string 19 /// 4、GetArrayStr(List list) 得到数组列表以逗号分隔的字符串 20 /// 5、GetArrayValueStr(Dictionary<int, int> list)得到数组列表以逗号分隔的字符串 21 /// 6、DelLastComma(string str)删除最后结尾的一个逗号 22 /// 7、DelLastChar(string str, string strchar)删除最后结尾的指定字符后的字符 23 /// 8、ToSBC(string input)转全角的函数(SBC case) 24 /// 9、ToDBC(string input)转半角的函数(SBC case) 25 /// 10、GetSubStringList(string o_str, char sepeater)把字符串按照指定分隔符装成 List 去除重复 26 /// 11、GetCleanStyle(string StrList, string SplitString)将字符串样式转换为纯字符串 27 /// 12、GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error)将字符串转换为新样式 28 /// 13、SplitMulti(string str, string splitstr)分割字符串 29 /// 14、SqlSafeString(string String, bool IsDel) 30 /// </summary> 31 public class StringHelper 32 { 33 /// <summary> 34 /// 把字符串按照分隔符转换成 List 35 /// </summary> 36 /// <param name="str">源字符串</param> 37 /// <param name="speater">分隔符</param> 38 /// <param name="toLower">是否转换为小写</param> 39 /// <returns></returns> 40 public static List<string> GetStrArray(string str, char speater, bool toLower) 41 { 42 List<string> list = new List<string>(); 43 string[] ss = str.Split(speater); 44 foreach (string s in ss) 45 { 46 if (!string.IsNullOrEmpty(s) && s != speater.ToString()) 47 { 48 string strVal = s; 49 if (toLower) 50 { 51 strVal = s.ToLower(); 52 } 53 list.Add(strVal); 54 } 55 } 56 return list; 57 } 58 /// <summary> 59 /// 把字符串转 按照, 分割 换为数据 60 /// </summary> 61 /// <param name="str"></param> 62 /// <returns></returns> 63 public static string[] GetStrArray(string str) 64 { 65 return str.Split(new Char[] { ',' }); 66 } 67 /// <summary> 68 /// 把 List<string> 按照分隔符组装成 string 69 /// </summary> 70 /// <param name="list"></param> 71 /// <param name="speater"></param> 72 /// <returns></returns> 73 public static string GetArrayStr(List<string> list, string speater) 74 { 75 StringBuilder sb = new StringBuilder(); 76 for (int i = 0; i < list.Count; i++) 77 { 78 if (i == list.Count - 1) 79 { 80 sb.Append(list[i]); 81 } 82 else 83 { 84 sb.Append(list[i]); 85 sb.Append(speater); 86 } 87 } 88 return sb.ToString(); 89 } 90 /// <summary> 91 /// 得到数组列表以逗号分隔的字符串 92 /// </summary> 93 /// <param name="list"></param> 94 /// <returns></returns> 95 public static string GetArrayStr(List<int> list) 96 { 97 StringBuilder sb = new StringBuilder(); 98 for (int i = 0; i < list.Count; i++) 99 { 100 if (i == list.Count - 1) 101 { 102 sb.Append(list[i].ToString()); 103 } 104 else 105 { 106 sb.Append(list[i]); 107 sb.Append(","); 108 } 109 } 110 return sb.ToString(); 111 } 112 /// <summary> 113 /// 得到数组列表以逗号分隔的字符串 114 /// </summary> 115 /// <param name="list"></param> 116 /// <returns></returns> 117 public static string GetArrayValueStr(Dictionary<int, int> list) 118 { 119 StringBuilder sb = new StringBuilder(); 120 foreach (KeyValuePair<int, int> kvp in list) 121 { 122 sb.Append(kvp.Value + ","); 123 } 124 if (list.Count > 0) 125 { 126 return DelLastComma(sb.ToString()); 127 } 128 else 129 { 130 return ""; 131 } 132 } 133 134 #region 删除最后一个字符之后的字符 135 136 /// <summary> 137 /// 删除最后结尾的一个逗号 138 /// </summary> 139 public static string DelLastComma(string str) 140 { 141 return str.Substring(0, str.LastIndexOf(",")); 142 } 143 144 /// <summary> 145 /// 删除最后结尾的指定字符后的字符 146 /// </summary> 147 public static string DelLastChar(string str, string strchar) 148 { 149 return str.Substring(0, str.LastIndexOf(strchar)); 150 } 151 152 #endregion 153 154 /// <summary> 155 /// 转全角的函数(SBC case) 156 /// </summary> 157 /// <param name="input"></param> 158 /// <returns></returns> 159 public static string ToSBC(string input) 160 { 161 //半角转全角: 162 char[] c = input.ToCharArray(); 163 for (int i = 0; i < c.Length; i++) 164 { 165 if (c[i] == 32) 166 { 167 c[i] = (char)12288; 168 continue; 169 } 170 if (c[i] < 127) 171 c[i] = (char)(c[i] + 65248); 172 } 173 return new string(c); 174 } 175 176 /// <summary> 177 /// 转半角的函数(SBC case) 178 /// </summary> 179 /// <param name="input">输入</param> 180 /// <returns></returns> 181 public static string ToDBC(string input) 182 { 183 char[] c = input.ToCharArray(); 184 for (int i = 0; i < c.Length; i++) 185 { 186 if (c[i] == 12288) 187 { 188 c[i] = (char)32; 189 continue; 190 } 191 if (c[i] > 65280 && c[i] < 65375) 192 c[i] = (char)(c[i] - 65248); 193 } 194 return new string(c); 195 } 196 197 /// <summary> 198 /// 把字符串按照指定分隔符装成 List 去除重复 199 /// </summary> 200 /// <param name="o_str"></param> 201 /// <param name="sepeater"></param> 202 /// <returns></returns> 203 public static List<string> GetSubStringList(string o_str, char sepeater) 204 { 205 List<string> list = new List<string>(); 206 string[] ss = o_str.Split(sepeater); 207 foreach (string s in ss) 208 { 209 if (!string.IsNullOrEmpty(s) && s != sepeater.ToString()) 210 { 211 list.Add(s); 212 } 213 } 214 return list; 215 } 216 217 218 #region 将字符串样式转换为纯字符串 219 /// <summary> 220 /// 将字符串样式转换为纯字符串 221 /// </summary> 222 /// <param name="StrList"></param> 223 /// <param name="SplitString"></param> 224 /// <returns></returns> 225 public static string GetCleanStyle(string StrList, string SplitString) 226 { 227 string RetrunValue = ""; 228 //如果为空,返回空值 229 if (StrList == null) 230 { 231 RetrunValue = ""; 232 } 233 else 234 { 235 //返回去掉分隔符 236 string NewString = ""; 237 NewString = StrList.Replace(SplitString, ""); 238 RetrunValue = NewString; 239 } 240 return RetrunValue; 241 } 242 #endregion 243 244 #region 将字符串转换为新样式 245 /// <summary> 246 /// 将字符串转换为新样式 247 /// </summary> 248 /// <param name="StrList"></param> 249 /// <param name="NewStyle"></param> 250 /// <param name="SplitString"></param> 251 /// <param name="Error"></param> 252 /// <returns></returns> 253 public static string GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error) 254 { 255 string ReturnValue = ""; 256 //如果输入空值,返回空,并给出错误提示 257 if (StrList == null) 258 { 259 ReturnValue = ""; 260 Error = "请输入需要划分格式的字符串"; 261 } 262 else 263 { 264 //检查传入的字符串长度和样式是否匹配,如果不匹配,则说明使用错误。给出错误信息并返回空值 265 int strListLength = StrList.Length; 266 int NewStyleLength = GetCleanStyle(NewStyle, SplitString).Length; 267 if (strListLength != NewStyleLength) 268 { 269 ReturnValue = ""; 270 Error = "样式格式的长度与输入的字符长度不符,请重新输入"; 271 } 272 else 273 { 274 //检查新样式中分隔符的位置 275 string Lengstr = ""; 276 for (int i = 0; i < NewStyle.Length; i++) 277 { 278 if (NewStyle.Substring(i, 1) == SplitString) 279 { 280 Lengstr = Lengstr + "," + i; 281 } 282 } 283 if (Lengstr != "") 284 { 285 Lengstr = Lengstr.Substring(1); 286 } 287 //将分隔符放在新样式中的位置 288 string[] str = Lengstr.Split(','); 289 foreach (string bb in str) 290 { 291 StrList = StrList.Insert(int.Parse(bb), SplitString); 292 } 293 //给出最后的结果 294 ReturnValue = StrList; 295 //因为是正常的输出,没有错误 296 Error = ""; 297 } 298 } 299 return ReturnValue; 300 } 301 #endregion 302 303 /// <summary> 304 /// 分割字符串 305 /// </summary> 306 /// <param name="str"></param> 307 /// <param name="splitstr"></param> 308 /// <returns></returns> 309 public static string[] SplitMulti(string str, string splitstr) 310 { 311 string[] strArray = null; 312 if ((str != null) && (str != "")) 313 { 314 strArray = new Regex(splitstr).Split(str); 315 } 316 return strArray; 317 } 318 public static string SqlSafeString(string String, bool IsDel) 319 { 320 if (IsDel) 321 { 322 String = String.Replace("'", ""); 323 String = String.Replace("\"", ""); 324 return String; 325 } 326 String = String.Replace("'", "'"); 327 String = String.Replace("\"", """); 328 return String; 329 } 330 331 #region 获取正确的Id,如果不是正整数,返回0 332 /// <summary> 333 /// 获取正确的Id,如果不是正整数,返回0 334 /// </summary> 335 /// <param name="_value"></param> 336 /// <returns>返回正确的整数ID,失败返回0</returns> 337 public static int StrToId(string _value) 338 { 339 if (IsNumberId(_value)) 340 return int.Parse(_value); 341 else 342 return 0; 343 } 344 #endregion 345 #region 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。 346 /// <summary> 347 /// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外) 348 /// </summary> 349 /// <param name="_value">需验证的字符串。。</param> 350 /// <returns>是否合法的bool值。</returns> 351 public static bool IsNumberId(string _value) 352 { 353 return QuickValidate("^[1-9]*[0-9]*$", _value); 354 } 355 #endregion 356 #region 快速验证一个字符串是否符合指定的正则表达式。 357 /// <summary> 358 /// 快速验证一个字符串是否符合指定的正则表达式。 359 /// </summary> 360 /// <param name="_express">正则表达式的内容。</param> 361 /// <param name="_value">需验证的字符串。</param> 362 /// <returns>是否合法的bool值。</returns> 363 public static bool QuickValidate(string _express, string _value) 364 { 365 if (_value == null) return false; 366 Regex myRegex = new Regex(_express); 367 if (_value.Length == 0) 368 { 369 return false; 370 } 371 return myRegex.IsMatch(_value); 372 } 373 #endregion 374 375 376 #region 根据配置对指定字符串进行 MD5 加密 377 /// <summary> 378 /// 根据配置对指定字符串进行 MD5 加密 379 /// </summary> 380 /// <param name="s"></param> 381 /// <returns></returns> 382 public static string GetMD5(string s) 383 { 384 //md5加密 385 s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString(); 386 387 return s.ToLower().Substring(8, 16); 388 } 389 #endregion 390 391 #region 得到字符串长度,一个汉字长度为2 392 /// <summary> 393 /// 得到字符串长度,一个汉字长度为2 394 /// </summary> 395 /// <param name="inputString">参数字符串</param> 396 /// <returns></returns> 397 public static int StrLength(string inputString) 398 { 399 System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); 400 int tempLen = 0; 401 byte[] s = ascii.GetBytes(inputString); 402 for (int i = 0; i < s.Length; i++) 403 { 404 if ((int)s[i] == 63) 405 tempLen += 2; 406 else 407 tempLen += 1; 408 } 409 return tempLen; 410 } 411 #endregion 412 413 #region 截取指定长度字符串 414 /// <summary> 415 /// 截取指定长度字符串 416 /// </summary> 417 /// <param name="inputString">要处理的字符串</param> 418 /// <param name="len">指定长度</param> 419 /// <returns>返回处理后的字符串</returns> 420 public static string ClipString(string inputString, int len) 421 { 422 bool isShowFix = false; 423 if (len % 2 == 1) 424 { 425 isShowFix = true; 426 len--; 427 } 428 System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); 429 int tempLen = 0; 430 string tempString = ""; 431 byte[] s = ascii.GetBytes(inputString); 432 for (int i = 0; i < s.Length; i++) 433 { 434 if ((int)s[i] == 63) 435 tempLen += 2; 436 else 437 tempLen += 1; 438 439 try 440 { 441 tempString += inputString.Substring(i, 1); 442 } 443 catch 444 { 445 break; 446 } 447 448 if (tempLen > len) 449 break; 450 } 451 452 byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); 453 if (isShowFix && mybyte.Length > len) 454 tempString += "…"; 455 return tempString; 456 } 457 #endregion 458 459 460 461 #region HTML转行成TEXT 462 /// <summary> 463 /// HTML转行成TEXT 464 /// </summary> 465 /// <param name="strHtml"></param> 466 /// <returns></returns> 467 public static string HtmlToTxt(string strHtml) 468 { 469 string[] aryReg ={ 470 @"<script[^>]*?>.*?</script>", 471 @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", 472 @"([\r\n])[\s]+", 473 @"&(quot|#34);", 474 @"&(amp|#38);", 475 @"&(lt|#60);", 476 @"&(gt|#62);", 477 @"&(nbsp|#160);", 478 @"&(iexcl|#161);", 479 @"&(cent|#162);", 480 @"&(pound|#163);", 481 @"&(copy|#169);", 482 @"&#(\d+);", 483 @"-->", 484 @"<!--.*\n" 485 }; 486 487 string newReg = aryReg[0]; 488 string strOutput = strHtml; 489 for (int i = 0; i < aryReg.Length; i++) 490 { 491 Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase); 492 strOutput = regex.Replace(strOutput, string.Empty); 493 } 494 495 strOutput.Replace("<", ""); 496 strOutput.Replace(">", ""); 497 strOutput.Replace("\r\n", ""); 498 499 500 return strOutput; 501 } 502 #endregion 503 504 #region 判断对象是否为空 505 /// <summary> 506 /// 判断对象是否为空,为空返回true 507 /// </summary> 508 /// <typeparam name="T">要验证的对象的类型</typeparam> 509 /// <param name="data">要验证的对象</param> 510 public static bool IsNullOrEmpty<T>(T data) 511 { 512 //如果为null 513 if (data == null) 514 { 515 return true; 516 } 517 518 //如果为"" 519 if (data.GetType() == typeof(String)) 520 { 521 if (string.IsNullOrEmpty(data.ToString().Trim())) 522 { 523 return true; 524 } 525 } 526 527 //如果为DBNull 528 if (data.GetType() == typeof(DBNull)) 529 { 530 return true; 531 } 532 533 //不为空 534 return false; 535 } 536 537 /// <summary> 538 /// 判断对象是否为空,为空返回true 539 /// </summary> 540 /// <param name="data">要验证的对象</param> 541 public static bool IsNullOrEmpty(object data) 542 { 543 //如果为null 544 if (data == null) 545 { 546 return true; 547 } 548 549 //如果为"" 550 if (data.GetType() == typeof(String)) 551 { 552 if (string.IsNullOrEmpty(data.ToString().Trim())) 553 { 554 return true; 555 } 556 } 557 558 //如果为DBNull 559 if (data.GetType() == typeof(DBNull)) 560 { 561 return true; 562 } 563 564 //不为空 565 return false; 566 } 567 #endregion 568 } 569 }