Replacing characters with escape sequences


/ Published in: C#
Save to your folder(s)

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?


Copy this code and paste it in your HTML
  1. /* solution 1*/
  2. static string Escape1(string source, char[] escapeChars, char escape) {
  3. int i = source.IndexOfAny(escapeChars);
  4. while (i != -1) {
  5. source = source.Insert(i, escape.ToString());
  6. i = source.IndexOfAny(escapeChars, i + 2);
  7. }
  8. return source.ToString();
  9. }
  10.  
  11. /* solution 2*/
  12. static string Escape2(string source, char[] escapeChars, char escape) {
  13. StringBuilder s = new StringBuilder();
  14. int j = 0;
  15. int i = source.IndexOfAny(escapeChars);
  16. while (i != -1) {
  17. s.Append(source.Substring(j, i - j));
  18. s.Append(escape);
  19. j = i;
  20. i = source.IndexOfAny(escapeChars, j + 1);
  21. }
  22. s.Append(source.Substring(j));
  23. return s.ToString();
  24. }

URL: http://www.codeproject.com/KB/string/string_optimizations.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.