persianLife
persianLife

Reputation: 1225

check if the first element of a string is positive integer

I need to check if the first element of a string is positive integer in C#. is there a smart Way to do this? Fx

string str = "2001";
if (str.First() == isANumber) {
...                                
}

Upvotes: 1

Views: 10333

Answers (8)

Ivan Golović
Ivan Golović

Reputation: 8832

You can try with this:

string s = "1sdfa";
bool isDigit = char.IsDigit(s[0]);

Also, if you wanted additional checks on string, you could do them like this:

bool isDigit = !string.IsNullOrEmpty(s) && char.IsDigit(s[0]);

Upvotes: 11

Habib
Habib

Reputation: 223207

You can use char.IsDigit method to check if the first character is a digit or not.

if(char.IsDigit(str[0]))
    Console.WriteLine("Starting character is positive digit");
else
    Console.WriteLine("Starting character is not a digit");

Its better if you can check the length of the string before accessing its index 0

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98740

You should use Char.IsDigit() method.

Indicates whether the specified Unicode character is categorized as a decimal digit.

Like;

string str = "2001";
if (Char.IsDigit(str[0]))
{
    Console.WriteLine ("Positive digit");
}
else
{
    Console.WriteLine ("Not digit");
}

Here is a DEMO.

Upvotes: 2

Neel
Neel

Reputation: 11721

hello u can use this...

string something = "some string";
bool isDigit = char.IsDigit(something[0]);

Upvotes: 0

whastupduck
whastupduck

Reputation: 1166

string str = "2001";

if (char.IsDigit(str.First())
{
   if(Convert.toInt32(str.First().ToString()) >= 0)
   {
     // positive integer
   }
}

Upvotes: 0

daryal
daryal

Reputation: 14919

if(Char.IsDigit(str.First()))
{
}

Upvotes: 0

sll
sll

Reputation: 62484

I believe if no sign then it is positive? So just check whether the first sybmol is not "-".

EDIT: As Mark noted in a comment below - it may depend on a culture which is used.

Upvotes: 3

Tigran
Tigran

Reputation: 62248

Can use Char.IsDigit

Char.IsDigit(str[0])

Upvotes: 2

Related Questions