简体   繁体   English

字符串格式和十六进制字符

[英]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? 为什么\\ x05没有被替换?

The format for the argument should be set in the format specifier, otherwise you're just inserting a literal "\\x". 参数的格式应该在格式说明符中设置,否则你只是插入一个文字“\\ 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: 或者你可以从一个真正的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM