Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting a tab stored as a string into a char in C#

I’m trying to convert a value retrieved from a deserialized XML file into a char.

<Delimiter>\t</Delimiter>

When I deserializing this XML into an object with a string property it becomes:

"\\t"

However, when I try to use the following code to get a char:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

char c = Convert.ToChar(stringValue);

I get the exception:

System.FormatException: 'String must be exactly one character long.'

If execute this code, it works:

char c = Convert.ToChar("\t");

How to I convert my string "\\t" into "\t" in order to convert it to a char?

I tried str = str.Replace("\\\\", "\\") but that didn’t seem to get rid of the escape backslash.

>Solution :

The literal \t is interpretted by C# as a single tab (0x9) character before calling .ToChar().

Additionally, you are NOT getting \\t (three characters) as a result of deserializing that xml. You are getting (\t) (two characters), but the debugger is trying to be overly helpful and escaping the \ escape character.

So, how do you convert the two \ and t characters and get the final tab (0x9) character result?

You can use Regex.Unescape() for this.

See it work here:

https://dotnetfiddle.net/OYE2Nf

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading