如何在C#中获取string的ASCII值

我想要在C#中的string中获取字符的ASCII值。

如果我的string的值是“9quali52ty3”,我想要一个数组,每个11个字符的ASCII值。

我如何获得C#中的ASCII值?

来自MSDN

string value = "9quali52ty3"; // Convert the string into a byte[]. byte[] asciiBytes = Encoding.ASCII.GetBytes(value); 

您现在有一个字节的ASCII值的数组。 我得到了以下几点:

57 113 117 97 108 105 53 50 116 121 51

 string s = "9quali52ty3"; foreach(char c in s) { Console.WriteLine((int)c); } 

这应该工作:

 string s = "9quali52ty3"; byte[] ASCIIValues = Encoding.ASCII.GetBytes(s); foreach(byte b in ASCIIValues) { Console.WriteLine(b); } 

你的意思是你只想要字母而不是数字? 所以你想要“质量”呢? 你可以使用Char.IsLetter或者Char.IsDigit来一个一个地过滤掉它们。

 string s = "9quali52ty3"; StringBuilder result = new StringBuilder(); foreach(char c in s) { if (Char.IsLetter(c)) result.Add(c); } Console.WriteLine(result); // quality 
 byte[] asciiBytes = Encoding.ASCII.GetBytes("Y"); foreach (byte b in asciiBytes) { MessageBox.Show("" + b); } 
 string value = "mahesh"; // Convert the string into a byte[]. byte[] asciiBytes = Encoding.ASCII.GetBytes(value); for (int i = 0; i < value.Length; i++) { Console.WriteLine(value.Substring(i, 1) + " as ASCII value of: " + asciiBytes[i]); } 
 string text = "ABCD"; for (int i = 0; i < text.Length; i++) { Console.WriteLine(text[i] + " => " + Char.ConvertToUtf32(text, i)); } 

如果我没有记错,ASCII值是Unicode编号的低七位的数字。

如果你想要string中的每个字符的charcode,你可以做这样的事情:

 char[] chars = "9quali52ty3".ToCharArray(); 

您可以使用以下方式删除BOM :

 //Create a character to compare BOM char byteOrderMark = (char)65279; if (sourceString.ToCharArray()[0].Equals(byteOrderMark)) { targetString = sourceString.Remove(0, 1); } 

该程序将接受多个字符并输出其ASCII值:

 using System; class ASCII { public static void Main(string [] args) { string s; Console.WriteLine(" Enter your sentence: "); s = Console.ReadLine(); foreach (char c in s) { Console.WriteLine((int)c); } } } 

之前的回应者已经回答了这个问题,但没有提供标题引导我期望的信息。 我有一个方法返回一个字符的string,但我想要一个字符,我可以转换为hex。 下面的代码演示了我想我会发现什么,希望对别人有帮助。

  string s = "\ta£\x0394\x221A"; // tab; lower case a; pound sign; Greek delta; // square root Debug.Print(s); char c = s[0]; int i = (int)c; string x = i.ToString("X"); c = s[1]; i = (int)c; x = i.ToString("X"); Debug.Print(c.ToString() + " " + i.ToString() + " " + x); c = s[2]; i = (int)c; x = i.ToString("X"); Debug.Print(c.ToString() + " " + i.ToString() + " " + x); c = s[3]; i = (int)c; x = i.ToString("X"); Debug.Print(c.ToString() + " " + i.ToString() + " " + x); c = s[4]; i = (int)c; x = i.ToString("X"); Debug.Print(c.ToString() + " " + i.ToString() + " " + x); 

以上代码将以下内容输出到即时窗口:

 a£Δ√ 

一个97 61

£163 A3

Δ916 394

√8730 221A

或者在LINQ中:

string value = "9quali52ty3";

var ascii_values = value.Select(x => (int)x);

var as_hex = value.Select(x => ((int)x).ToString("X02"));

我想要在C#中的string中获取字符的ASCII值。

每个人都在这个结构中给予答案。 如果我的string的值是“9quali52ty3”,我想要一个数组,每个11个字符的ASCII值。

但是在控制台中,我们的工作坦率,所以我们得到一个字符,如果我错了,打印ASCII码,请纠正我的答案。

  static void Main(string[] args) { Console.WriteLine(Console.Read()); Convert.ToInt16(Console.Read()); Console.ReadKey(); }