-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathStringExtensions.cs
104 lines (84 loc) · 2.74 KB
/
StringExtensions.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
//************************************************************************************************
// Copyright © 2020 Steven M Cohn. All rights reserved.
//************************************************************************************************
namespace ResxTranslator
{
using System;
using System.Text;
/// <summary>
/// This is a customization of the System.Security.SecurityElement.Escape method
/// that ignores apostrophies (') and double-quotes (")
/// </summary>
internal static class StringExtensions
{
private static readonly string[] EscapePairs = new string[]
{
// these must be all once character escape sequences or a new escaping algorithm is needed
"<", "<",
">", ">",
"&", "&"
};
private static readonly char[] EscapeChars = new char[] { '<', '>', '&' };
/// <summary>
/// Compares a string against the given instance, as non-case-sensitive.
/// </summary>
/// <param name="s">The string instance</param>
/// <param name="value">The other string for comparison</param>
/// <returns>True if the instance contains at least one occurance of value</returns>
public static bool ContainsICIC(this string s, string value)
{
return s.IndexOf(value, StringComparison.InvariantCultureIgnoreCase) >= 0;
}
/// <summary>
/// Escapes special XML characters in the given text values so those characters
/// survive round-trips as user-input text
/// </summary>
/// <param name="str">The user input string</param>
/// <returns>The user string with special XML characters escaped</returns>
public static string XmlEscape(this string str)
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
do
{
index = str.IndexOfAny(EscapeChars, newIndex);
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append(str, newIndex, strLen - newIndex);
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append(str, newIndex, index - newIndex);
sb.Append(GetEscapeSequence(str[index]));
newIndex = (index + 1);
}
}
while (true);
// no normal exit is possible
}
private static string GetEscapeSequence(char c)
{
int iMax = EscapePairs.Length;
for (int i = 0; i < iMax; i += 2)
{
string strEscSeq = EscapePairs[i];
string strEscValue = EscapePairs[i + 1];
if (strEscSeq[0] == c)
return strEscValue;
}
return c.ToString();
}
}
}