Revision: 22358
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at January 10, 2010 22:45 by quangnd
Initial Code
/* solution 1*/
static string Escape1(string source, char[] escapeChars, char escape) {
int i = source.IndexOfAny(escapeChars);
while (i != -1) {
source = source.Insert(i, escape.ToString());
i = source.IndexOfAny(escapeChars, i + 2);
}
return source.ToString();
}
/* solution 2*/
static string Escape2(string source, char[] escapeChars, char escape) {
StringBuilder s = new StringBuilder();
int j = 0;
int i = source.IndexOfAny(escapeChars);
while (i != -1) {
s.Append(source.Substring(j, i - j));
s.Append(escape);
j = i;
i = source.IndexOfAny(escapeChars, j + 1);
}
s.Append(source.Substring(j));
return s.ToString();
}
Initial URL
http://www.codeproject.com/KB/string/string_optimizations.aspx
Initial Description
Another common task when working with strings is to replace a set of characters with a set of escape sequences. Sometimes the replacement is very easy - you only have to place a backslash (or another character) before every occurrence of an escaped character.
Imagine the following scenario: you are building an RTF file and you want to insert a string into the file. The "{", "}", and "\" characters have a special meaning in RTF and, therefore, must be preceded with a backslash. The question is: what is the fastest way to replace each of the characters with a corresponding escape sequence?
Initial Title
Replacing characters with escape sequences
Initial Tags
c
Initial Language
C#