C#扩展格式化方法

C#扩展格式化方法

源代码:

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
/// <summary>
/// Formats the string according to the specified mask
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="mask">The mask for formatting. Like "A##-##-T-###Z"</param>
/// <returns>The formatted string</returns>
public static string FormatWithMask(this string input, string mask)
{
if (input.IsNullOrEmpty()) return input;
var output = string.Empty;
var index = 0;
foreach (var m in mask)
{
if (m == '#')
{
if(index < input.Length)
{
output += input[index];
index++;
}
}
else
output += m;
}
return output;
}

示例:

1
2
3
4
5
6
7
8
var s = "aaaaaaaabbbbccccddddeeeeeeeeeeee".FormatWithMask("Hello ########-#A###-####-####-############ Oww");
s.ShouldEqual("Hello aaaaaaaa-bAbbb-cccc-dddd-eeeeeeeeeeee Oww");

var s = "abc".FormatWithMask("###-#");
s.ShouldEqual("abc-");

var s = "".FormatWithMask("Hello ########-#A###-####-####-############ Oww");
s.ShouldEqual("");
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×