开发者

String format and hex chars

can someone explain why开发者_开发技巧 this doesnt work:

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

Output is:

\x05{0} : \x05INSERT TEXT

why does the \x05 not get replaced?


The format for the argument should be set in the format specifier, otherwise you're just inserting a literal "\x". Like this:

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

Don't confuse how you represent a hex literal in source code with what you would print in a formatted string, they are different things.


To put a literal char in a string, just make sure that the compiler knows it's a 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 out with a real char:

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

Take your pick.


Is this what you need?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜