如何在C#中获取字符的ASCII值 [英] How to get ASCII value of characters in C#

查看:877
本文介绍了如何在C#中获取字符的ASCII值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在C#中的字符串,我将其转换为字符数组& ;;需要获取字符串中每个字符的ASCII值.

Below is my string in C# which I am converting it to Character array & in need to get the ASCII value of each character in the string.

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

在谷歌搜索时,我得到了很多链接,但是没有一个可以满足我的需求.

On googling I got number of links but none of them suffice my need.

  • How to get ASCII value of string in C#
  • https://www.codeproject.com/Questions/516802/ConvertingpluscharsplustoplusASCIIplusinplusC

我需要获取字符串中每个字符的ASCII值.???

I am in need to get the ASCII value of each character in string.???

高度赞赏任何帮助/建议.

Any help/suggestion highly appreciated.

推荐答案

string可以直接枚举为IEnumerable<char>.并且每个char都可以转换为整数以查看其UNICODE值"(代码点). UTF-16将ASCII的128个字符(0-127)映射到UNICODE代码点0-127(例如,请参见

A string can be directly enumerated to a IEnumerable<char>. And each char can be casted to a integer to see its UNICODE "value" (code point). UTF-16 maps the 128 characters of ASCII (0-127) to the UNICODE code points 0-127 (see for example https://en.wikipedia.org/wiki/Code_point), so you can directly print this number.

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#中获取字符的ASCII值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆