Monday, March 7, 2011

How to get ASCII value of string in C#

I want to get Ascii Value of string in C#

My string will have value like "9quali52ty3" this ,so if I just convert it to integer I don't get ascii values of numbers that are in the string

Can any one please help me with getting ascii values in C#

From stackoverflow
  • string s = "9quali52ty3";
    foreach(char c in s)
    {
      Console.WriteLine((int)c);
    }
    
    Lars Truijens : The resulting codes are Unicode numbers and could potentially contain non ASCII codes.
  • This should work:

    string s = "9quali52ty3";
    byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
    foreach(byte b in ASCIIValues) {
        Console.WriteLine(b);
    }
    
  • Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? You can use Char.IsLetter or Char.IsDigit to filter them out one by one.

    string s = "9quali52ty3";
    StringBuilder result = new StringBuilder();
    foreach(char c in s)
    {
      if (Char.IsLetter(c))  
        result.Add(c);
    }
    Console.WriteLine(result);  // quality
    
  • string text = "ABCD";
    for (int i = 0; i < text.Length; i++)
    {
      Console.WriteLine(text[i] + " => " + Char.ConvertToUtf32(text, i));
    }
    

    IIRC the ASCII value is the number of the lower 7 bits of the unicode number.

  • If you want the charcode for each character in the string, you could do something like this:

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

    Need a bit more information in the post to be more helpful.

  • From MSDN

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

    You now have an array of the ASCII value of the bytes. I got the following:

    57 113 117 97 108 105 53 50 116 121 51

0 comments:

Post a Comment