StringExtension.cs
2.42 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hh.Mes.Common
{
public static class StringExtension
{
/// <summary>针对单个格式字符串调用 "welcome to {0}! welcome to {1}!".FormatWith("lsw", "wisdom"); 未做null判断
/// </summary>
public static string FormatWith(this string format, params object[] args)
{
var capacity = format.Length + args.Select(p => p.ToString()).Sum(p => p.Length);
Console.WriteLine(capacity);
var stringBuilder = new StringBuilder(capacity);
stringBuilder.AppendFormat(format, args);
return stringBuilder.ToString();
}
/// <summary>针对多个格式字符串 new string[] { "welcome to {0}!", " welcome to {1}!" }.FormatWith("lsw", "wisdom");
/// </summary>
public static string FormatWith(this IEnumerable<string> formats, params object[] args)
{
var capacity = formats.Where(f => !string.IsNullOrEmpty(f)).Sum(f => f.Length) +
args.Where(a => a != null).Select(p => p.ToString()).Sum(p => p.Length);
var stringBuilder = new StringBuilder(capacity);
foreach (var f in formats)
{
if (!string.IsNullOrEmpty(f))
{
stringBuilder.AppendFormat(f, args);
}
}
return stringBuilder.ToString();
}
/// <summary>
/// 字符 特殊符号替换
/// </summary>
public static string StrJsonReplace(this string str)
{
var sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
var c = str[i];
switch (c)
{
case '\"':
case '\'':
case '\\':
case '/':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t':
sb.Append(" ");
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString().Replace("CNOOCLegLineUAT", " ").Replace("SqlSugar", "xxx").Replace("Sugar", "xxx").Replace("Sql", "xxx");
}
}
}