gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:45:16 26 4
gpt4 key购买 nike

我试图找到一种方法来使用 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com