-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensions.cs
97 lines (83 loc) · 3.03 KB
/
Extensions.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
using System.Text;
namespace vz_generator
{
public static class Extensions
{
public static string EnsureEndsWith(this string origin, char c)
{
if (origin.EndsWith(c))
{
return origin;
}
return origin + c;
}
public static string EnsureEndsWithDirectorySeparatorChar(this string path)
{
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path), "path should not empty!");
}
if (Path.EndsInDirectorySeparator(path))
{
return path;
}
else
{
return path + Path.DirectorySeparatorChar;
}
}
//https://github.com/personball/abpluz.abp/blob/master/src/Abpluz.Abp/System/AbpluzStringExtensions.cs
public static string ReplaceAsSpan(this string str, Dictionary<string, string> map)
{
ReadOnlySpan<char> content = str.AsSpan();
StringBuilder builder = new StringBuilder();
var keyPosMap = new Dictionary<string, List<int>>();
var posSortedMapKey = new SortedDictionary<int, string>();
foreach (var key in map.Keys)
{
int accPos = 0;
int keyLen = key.Length;
ReadOnlySpan<char> keySpan = key.AsSpan();
ReadOnlySpan<char> contentTmp = content;
while (true)
{
int startPos = contentTmp.IndexOf(keySpan);
if (startPos == -1)
{
break;
}
if (keyPosMap.ContainsKey(key))
{
keyPosMap[key].Add(accPos + startPos);// 相对于原始字串的index
}
else
{
keyPosMap.Add(key, new List<int> { accPos + startPos });
}
if (!posSortedMapKey.ContainsKey(accPos + startPos))
{
posSortedMapKey.Add(accPos + startPos, key);
}
contentTmp = contentTmp.Slice(startPos + keyLen);
accPos += startPos + keyLen;
}
}
// slice and merge
var start = 0;
foreach (var pos in posSortedMapKey.Keys)
{
var key = posSortedMapKey[pos];
var value = map[key];
builder.Append(content.Slice(start, pos - start));
start = pos + key.Length;
builder.Append(value);
}
// tail
if (start < content.Length)
{
builder.Append(content.Slice(start, content.Length - start));
}
return builder.ToString();
}
}
}