We store ContentDelimiter config (which we use to delimite the content) in Database as string (which could be "tab", i.e. \t , or new line \r\n)
Later on we would like to use this config, how would I go about converting \t
(which is string, not chat) to tab char ?
Example:
string delimiterConfig = config.GetDelimiter();
char[] delimiter = ConvertConfig(delimiterConfig);
How would ConvertConfig will look like so that it will parse all escaped strings back into chars so that "\t" string will become \t
char.
Any elegant solutions without using case statements and replace ?
If by "better" solution, you mean 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 against this input:
var input = new String('\\', 0x1000);
If by "better" you mean easier to read and maintain, then the Regex solution probably wins. There might also be bugs in my solution; I didn't test it very thoroughly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With