Nika
Nika

Reputation: 379

Check if the string "00" is a number and return false in C#

I need to check if a string is a number and then I need to check the arrange of this number. So I use the TryParse method for it but I need for strings "00" or "01" or similiar get false. With my code I get true:

var isNum = int.TryParse(s, out int n);

So I have a trouble with such strings ("00", "01" etc) because I got true but I want to get false

Upvotes: 0

Views: 448

Answers (5)

user13523921
user13523921

Reputation:

Just to make the list complete, here it is using a logical exclusive OR:

(((byte)s[0] ^ 0x30) == 0)

Here an example:

string[] inputs = new string[] {
    "01",
    "00",
    "100",
    "0",
    "1",
    "010"
};

foreach (string s in inputs) {
    if ((s.Length > 1) && (((byte)s[0] ^ 0x30) == 0)) {
        System.Diagnostics.Debug.WriteLine("invalid input: " + s);
    }
    else
    {
        int i;
        int.TryParse(s, out i);
        System.Diagnostics.Debug.WriteLine("valid input: " + i.ToString());
    }
}

The result:

invalid input: 01
invalid input: 00
valid input: 100
valid input: 0
valid input: 1
invalid input: 010

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 142233

You can use regular expressions to validate that your string is an integer number not prefixed with 0s:

var isNumberNotPrefixedWith0 = Regex.IsMatch(s, @"^(0|[1-9]\d*)$");

The full regex explanation is here.

Upvotes: 1

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

simply (reverse-) compare the result as a string afterwards:

var isNum = int.TryParse(s, out int n);
isNum = n.ToString().Equals(s) 

This assures in any case (and with the correct comparison in any culture) that s is a true int.

Upvotes: 3

Nopesound
Nopesound

Reputation: 510

Try this

var isNum = !s.StartsWith("0") && int.TryParse(s, out int n);

Upvotes: 0

Vivek Nuna
Vivek Nuna

Reputation: 1

you can also add a check if (s.StartsWith("0") == false). so it will return false for all the strings with leading 0.

so you can use the code.

bool isNum = s.StartsWith("0") == false && int.TryParse(s, out int n);

Upvotes: 0

Related Questions