Reputation: 1225
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
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
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
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
Reputation: 11721
hello u can use this...
string something = "some string";
bool isDigit = char.IsDigit(something[0]);
Upvotes: 0
Reputation: 1166
string str = "2001";
if (char.IsDigit(str.First())
{
if(Convert.toInt32(str.First().ToString()) >= 0)
{
// positive integer
}
}
Upvotes: 0
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