String format and hexadecimal characters

can someone explain why this is not working:

string f = string.Format("\\x{0:00}{{0}}", 5);
string o = string.Format(f, "INSERT TEXT");
System.Diagnostics.Debug.WriteLine(f + " : " + o);

Output:

\x05{0} : \x05INSERT TEXT

Why is \ x05 not replaced?

+5
source share
3 answers

The format of the argument must be specified in the format specifier, otherwise you simply insert the literal "\ x". Like this:

// "5" as a lowercase 2-digit hex
string f = string.Format("{0:x2}{{0}}", 5);

Do not confuse how you represent the hexadecimal literal in the source code with the fact that you will print in a formatted string, these are two different things.

+10
source

To put a char literal in a string, just make sure the compiler knows its char.

string f = string.Format("{0}", (char)5);
string g = string.Format("{0}", Convert.ToChar(5));
string h = string.Format("{0}", char.ConvertFromUtf32(5));

or you can start with a real char:

string i = string.Format("{0}", '\x05');
string j = string.Format("{0}", '\u0005');
string k = string.Format("{0}", '\U00000005');

Make a choice.

+6
source

, ?

  int x = 5;
  string f = string.Format("\\x{0:x2}{1}", x, "INSERT TEXT");
  Console.WriteLine(f);
0

All Articles