简体   繁体   English

如何将 int 值存储和表示为 char (C#)

[英]How to store and represent an int value as a char (C#)

Im not sure if the title is well explained.我不确定标题是否得到很好的解释。 What I mean is getting this done:我的意思是完成这项工作:

int i = 3;
char id = (char)i:
Console.Writeline(i);
Console.Writeline(id);

and then getting the output in Console:然后在控制台中获取 output:

3 3

3 3

But (obviously) I get the output:但是(显然)我得到了 output:

在此处输入图像描述

I would like to be able to store as a character the same value of the int variable, not the associated symbol code.我希望能够将 int 变量的相同值存储为字符,而不是关联的符号代码。

Assuming you mean an integer in the range 0 thru 9, then offset the value by the character code for the zero character in ASCII - which happens to be 48, but there's no need to know that here - just use the character itself:假设您的意思是 integer 在 0 到 9 的范围内,然后将值偏移 ASCII 中零字符的字符代码 - 恰好是 48,但这里不需要知道 - 只需使用字符本身:

int i = 3;
char id = (char)('0' + i);

If you mean any integer: ToString() is your friend (there isn't a char that can display the value of 42 or -3 , for example, since they need multiple characters).如果您的意思是任何 integer: ToString()是您的朋友(例如,没有可以显示42-3值的char ,因为它们需要多个字符)。

i.ToString() is what you are looking for. i.ToString()是您正在寻找的。

(char)i converts the value using the ASCII tables, 3 meaning ETX - End of TeXt and therefore showing you a weird symbol. (char)i使用 ASCII 表转换值,3 表示 ETX - TeXt 结束,因此向您显示一个奇怪的符号。

You could convert the int value to a string first.您可以先将 int 值转换为字符串。 If you still need it as a char, you can just place the string value inside a char variable by converting it.如果您仍然需要它作为 char,您可以通过转换将字符串值放入 char 变量中。 It would look like that:它看起来像这样:

int number = 3;
 string convertedNumber = Convert.ToString(number);
 char getChar = Convert.ToChar(convertedNumber);
 Console.WriteLine(getChar);

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

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