Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

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.

Upvotes: 2

Views: 787

Answers (3)

Manu
Manu

Reputation: 29143

you could achieve this with a regular expression

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

Upvotes: 1

magnattic
magnattic

Reputation: 12998

static bool IsNumeric(string str)
{
  foreach(char c in str)
    if(!char.IsDigit(c))
       return false;
  return true;
}

Upvotes: 2

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

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
}

Upvotes: 3

Related Questions