|
Back
Checking For Numeric Characters in a String Using C#
Here are a number of ways you can check a string for numeric characters:
Firstly you can create a simple function like:
public bool OnlyNumeric(string s) { int i = 0; while (i='0' && s[i]<='9') i++; return i==s.Length; }
You could also do the check using a try/catch and if exception is thrown do whetever you do when OnlyNumeric returns.
public bool OnlyNumeric(string s) { try { Convert.ToInt64(s); return true; } catch { return false; }
}
However with the second option exception handling is a performance expensive operation.
You could further simplify the solution by using char.IsNumber(...) in the while condition:
public bool OnlyNumeric(string s) { int i = 0; while (i < s.Length && char.IsNumber(s[i])) i++;
return i == s.Length; }
A further option is to use regular expressions. This regular expression ^[0-9]*$ means that:
- ^ from start of string
- [0-9] between 0-9
- [0-9]* all numbers
- $ end of string
string[] arrNumbers = {"12aa","123","111","aaa"}; Regex r = new Regex("^[0-9]*$"); foreach (string a in arrNumbers) { if (r.IsMatch(a)) { Console.WriteLine("this is a Number"); } else { Console.WriteLine("This is not a Number"); } }
The following regular expression pattern searches for any non numeric character and if found returns true.
Match m; m = Regex.Match(inputStr, @"[^\d]+|^$"); if( m.Success ) { MessageBox.Show("String was not all numeric characters"); } else { MessageBox.Show("String IS ALL numeric characters"); }
Note the use of "|^$" in the pattern is so that it will also catch an empty string.
Back
|