/ Published in: C#
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?
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?
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* 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) { 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(); }
URL: http://www.codeproject.com/KB/string/string_optimizations.aspx