.net - .NET 中 String.Format 的 %c 等价物是什么?

标签 .net c++-cli

我试图找到一种方法来使用 .NET 语言在 printf 样式函数中移植“%c”格式,但失败了。例如,我该如何写:

char code = 'a';
sprintf(text,"oops! %c",code);

在 C++/CLI 中我尝试了一些但他们没有给我 'a'!

编辑:

首先,我尝试将一些值格式化为字符“a”或“b”或“c”...环境是 VisualStudio 2008、CLI/CPP、.NET 3.5。我编写了测试代码来展示我所做的。

String^ text;
char    charC = 'a';
text = String::Format("(1) Oops! {0}",charC);
OutputDebugString(text);
char    charV = 1;
text = String::Format("(2) Oops! {0}",charV + 0x60);
OutputDebugString(text);
text = String::Format("(3) Oops! {0}",(char)(charV + 0x60));
OutputDebugString(text);
int intV = 1;
text = String::Format("(4) Oops! {0}",(char)(intV + 0x60));
OutputDebugString(text);

结果和我预想的不一样。

(1) Oops! 97
(2) Oops! 97
(3) Oops! 97
(4) Oops! 97

以上代码似乎与其他人建议的代码工作方式不同。我感到很抱歉,我应该在第一时间更详细地说明我所做的事情。

如果我们只有 {0} 来格式化变量,我们无法选择将其设置为像 'a' 这样的字符或像 '97' 这样的数字。而我没有得到'a',我想问一下怎么做。

编辑 2:

根据评论的建议,我将'char'更改为'Char'这样;

String^ text;
Char    charC = 'a';
text = String::Format("(1) Oops! {0}",charC);
OutputDebugString(text);
Char    charV = 1;
text = String::Format("(2) Oops! {0}",charV + 0x60);
OutputDebugString(text);
text = String::Format("(3) Oops! {0}",(Char)(charV + 0x60));
OutputDebugString(text);
int intV = 1;
text = String::Format("(4) Oops! {0}",(Char)(intV + 0x60));
OutputDebugString(text);

我得到了;

(1) Oops! a
(2) Oops! 97
(3) Oops! a
(4) Oops! a

所以“Char”而不是“char”似乎有效。

最佳答案

char 关键字在 C 和 C++ 语言中保持其原始含义,它在 MSVC++ 中是一个 8 位类型,.NET Framework 没有等效的字符类型,因此 String::Format () 将其视为 System::SByte 的别名。整数类型,因此您看到的是整数值而不是字符。

.NET使用utf-16编码的Unicode,System::Char是16位类型。在匹配 wchar_t 关键字的 MSVC++ 中。您可以直接使用,或者使用 Char 而不是 char

关于.net - .NET 中 String.Format 的 %c 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31411364/

相关文章:

c# - 弥补 SOA 中继承不足的模式

visual-studio - 为什么是 Intellisense "Unavailable for C++/CLI"?

c# - 扩展方法与反射(reflection)

.net - 向框架命名空间添加新类是一种好习惯吗?

c# - 比较两个数组并返回它们的余数

c# - Unity 和 Simple Injector 之间的 IoC 注册差异

c# - 任何 cpu 和 x64 之间的托管代码引用

c# - .NET 4.5 命名空间 'Standard'

c++-cli - 是否可以将托管字节数组转换为没有 pin_ptr 的 native 结构,这样就不会给 GC 带来太多 bug?

.net - 如何将 cli::array 从 native 代码转换为 native 数组?