开发者

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

开发者 https://www.devze.com 2023-01-24 14:11 出处:网络
I will have my string as follows String S=\"AB-1233-444\"; From this i would like to separate A开发者_Python百科B and would like to find out the ASCII for that 2 alphabets.You should be able to use

I will have my string as follows

String S="AB-1233-444";

From this i would like to separate A开发者_Python百科B 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);
    }
}


You can convert a character to a codepoint using this: (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);
      }
 }


You can use substring to get alphabets alone and use a for loop to store value of alphabets in an array and print it one by one

0

精彩评论

暂无评论...
验证码 换一张
取 消