开发者

C# numbers and Letters

开发者 https://www.devze.com 2023-02-09 11:18 出处:网络
I need my application to perform an action based on if the selected text is contains letters or anything except numbers dont do that.

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 eas开发者_如何学Cy 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+$")){...}
0

精彩评论

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