If with the βbestβ solution you speak faster:
static String Replace(String input) { if (input.Length <= 1) return input; // the input string can only get shorter // so init the buffer so we won't have to reallocate later char[] buffer = new char[input.Length]; int outIdx = 0; for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == '\\') { if (i < input.Length - 1) { switch (input[i + 1]) { case 'n': buffer[outIdx++] = '\n'; i++; continue; case 'r': buffer[outIdx++] = '\r'; i++; continue; case 't': buffer[outIdx++] = '\t'; i++; continue; } } } buffer[outIdx++] = c; } return new String(buffer, 0, outIdx); }
This is significantly faster than using Regex. Especially when I tested this input:
var input = new String('\\', 0x1000);
If βbetter,β you realize that itβs easier to read and maintain, then the Regex solution will probably win. There may be errors in my decision; I did not test it very carefully.
source share