简体   繁体   中英

C# numbers and Letters

I need my application to perform an action based on if the selected text is contains letters or anything except numbers dont do that.

How can I tell if a string is letters or numbers?

Its so easy but i can not write this code.

You can try to do it like this:

string myString = "100test200";
long myNumber;
if( long.TryParse( myString, out myNumber ){
  //text contains only numbers, and that number is now put into myNumber.
  //do your logic dependent of string being a number here
}else{
  //string is not a number. Do your logic according to the string containing letters here
}

If you want to see if the string contains one or more digits, and not all digits, use this logic instead.

if (myString.Any( char.IsDigit )){
  //string contains at least one digit
}else{
  //string contains no digits
}
static bool IsNumeric(string str)
{
  foreach(char c in str)
    if(!char.IsDigit(c))
       return false;
  return true;
}

you could achieve this with a regular expression

string str = "1029";
if(Regex.IsMatch(str,@"^\d+$")){...}

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