public static string Escape(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).
while (true)
{
index = str.IndexOfAny(s_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);
}
}
// no normal exit is possible
}