Home > Enterprise >  How to treat ASCII code as a string rather than it's character
How to treat ASCII code as a string rather than it's character

Time:09-27

When checking a string that contains an ASCII code e.g. ABC\x30XYZ, how can I read it as exactly that full string, rather than reading it as the string ABC0XYZ?

For example:

var value = "ABC\x30XYZ";
foreach(var c in value)
{
    Console.Write(c);
} 
// Desired output: ABC\x30XYZ
// Actual output: ABC0XYZ

I'm guessing I need to do something with Encoding but I'm struggling to find the solution. I feel like I'm missing something really obvious and am prepared to hang my head in shame when someone points this out.

CodePudding user response:

If you create the string yourself, you need to escape "\x30" ASCII notation for it to be treated as a string:

var value = "ABC\\x30XYZ";

If you want to parse ASCII codes out of an input string, you could use regex parsing like:

 var value = "ABC\\x30XYZ";
 var values = Regex.Matches(value, @"\\x[\d]{2}|.");
 foreach (var c in values)
 {
    Console.Write(c);
 }

Use an appropriate regex based on the input format you expect.

  • Related