// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text.RegularExpressions; public interface NumberChecker { bool IsNumber(string s); string Algorithm { get; } } public class Try1 : NumberChecker { public bool IsNumber(string s) { try { int.Parse(s); return true; } catch(FormatException) { return false; } } public string Algorithm { get { return "try catch"; } } } public class Try2 : NumberChecker { public bool IsNumber(string s) { for(int i = 0; i < s.Length; i++) { if(!Char.IsDigit(s[i])) { return false; } } return true; } public string Algorithm { get { return "for + IsDigit"; } } } public class Try3 : NumberChecker { private static Regex r = new Regex("^[0-9]+$",RegexOptions.Compiled); public bool IsNumber(string s) { return r.IsMatch(s); } public string Algorithm { get { return "regex ^[0-9]+$"; } } } public class Try4 : NumberChecker { private static Regex r = new Regex("^[\\d]+$",RegexOptions.Compiled); public bool IsNumber(string s) { return r.IsMatch(s); } public string Algorithm { get { return "regex ^[\\d]+$"; } } } public class Try5 : NumberChecker { public bool IsNumber(string s) { for(int i = 0; i < s.Length; i++) { if(s[i] < '0' || s[i] > '9') { return false; } } return true; } public string Algorithm { get { return "for + <>"; } } } public class Try6 : NumberChecker { private static char[] NONDIGIT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÆØÅæøå_-".ToCharArray(); public bool IsNumber(string s) { return s.IndexOfAny(NONDIGIT) < 0; } public string Algorithm { get { return "IndexOfAny"; } } } class TestClass { private const int N = 10000000; private static void Test(string title, string s, NumberChecker chk, bool expect) { bool res = !expect; long t1 = DateTime.Now.Ticks; for(int i = 0; i < N; i++) { res = chk.IsNumber(s); } long t2 = DateTime.Now.Ticks; if(res != expect) { Console.WriteLine(title + " : Error"); } else { Console.WriteLine(title + " : " + (t2 - t1)/10000000.0); } } private static void Test(NumberChecker chk) { Console.WriteLine(chk.Algorithm + ":"); Test("Short number", "1", chk, true); Test("Long number", "123456789", chk, true); Test("Invalid number", "ABC", chk, false); } public static void Main(string[] args) { //Test(new Try1()); Test(new Try2()); Test(new Try3()); Test(new Try4()); Test(new Try5()); Test(new Try6()); } }