服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 非常实用的C#字符串操作处理类StringHelper.cs

非常实用的C#字符串操作处理类StringHelper.cs

2022-01-17 12:54sanler C#

这篇文章主要为大家详细介绍了非常实用的C#字符串操作处理类StringHelper.cs,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

一个非常好的C#字符串操作处理类StringHelper.cs,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/// <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 = 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#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03