简体   繁体   中英

How to get ASCII for non-numeric characters in a given string

I will have my string as follows

String S="AB-1233-444";

From this i would like to separate AB and would like to find out the ASCII for that 2 alphabets.

You should be able to use LINQ to take care of that (testing the syntax now):

var asciiCodes = S.Where(c => char.IsLetter(c)).Select(c => (int)c);

Or if you don't want to use the LINQ-y version:

var characterCodes = new List<int>();

foreach(var c in S)
{
    if(char.IsLetter(c))
    {
        characterCodes.Add((int)c);
    }
}

您可以使用以下命令将字符转换为代码点: (int)'a'

To seperate (if you know that it's split on - you can use string.Split

To get the ASCII representation of 'A' for example, use the following code

int asciivalue = (int)'A';

So complete example might be

Dictionary<char,int> asciilist = new Dictionary<char,int>();
string s = "AB-1233-444";
string[] splitstrings = s.Split('-');
foreach( char c in splitstrings[0]){
  asciilist.Add( c, (int)c );
}
  var result = (from c in S.ToCharArray() where
   ((int)c >= (int)'a' &&
   (int)c <= (int)'z') || 
   ((int)c >= (int)'A' && 
   (int)c <= (int)'Z') select c).ToArray();

Non-linq version is as follows:

List<char> result = new List<char>();
foreach(char c in S)
{
  if(((int)c >= (int)'a' &&
     (int)c <= (int)'z') || 
     ((int)c >= (int)'A' && 
     (int)c <= (int)'Z'))
      {
        result.Add(c);
      }
 }

您可以使用子字符串单独获取字母,并使用for循环将字母值存储在数组中并逐个打印

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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