下面是我在 C#
中的字符串,我正在将其转换为字符数组,并且需要获取字符串中每个字符的 ASCII 值。
static void Main(string[] args)
{
string s = "Test";
var arr = s.ToCharArray();
foreach(var a in arr)
{
var n = Encoding.ASCII.GetByteCount(a.ToString());
Console.WriteLine(a);
Console.WriteLine(n);
}
}
这输出为
T
1
e
1
s
1
t
1
在 google 上我得到了很多链接,但没有一个能满足我的需要。
- How to get ASCII value of string in C#
- https://www.codeproject.com/Questions/516802/ConvertingpluscharsplustoplusASCIIplusinplusC
我需要获取字符串中每个字符的 ASCII 值。???
非常感谢任何帮助/建议。
最佳答案
A string
可以直接枚举成一个IEnumerable<char>
.每个 char
可以转换为整数以查看其 UNICODE“值”(代码点)。 UTF-16 将 ASCII (0-127) 的 128 个字符映射到 UNICODE 代码点 0-127(参见示例 https://en.wikipedia.org/wiki/Code_point ),因此您可以直接打印此数字。
string s = "Test";
foreach (char a in s)
{
if (a > 127)
{
throw new Exception(string.Format(@"{0} (code \u{1:X04}) is not ASCII!", a, (int)a));
}
Console.WriteLine("{0}: {1}", a, (int)a);
}
关于c# - C#中如何获取字符的ASCII值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43370754/