Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
public bool IsNumber(string s) { int size = s.Length; if(size == 0) return false; int numindex = -1; int dotindex = -1; int eindex = -1;//e index var possibleFirstChar = new List<char>(){'+','-','.'}; var digits = new List<char>(){'0','1','2','3','4','5','6','7','8','9'}; if(size == 1 && !digits.Contains(s[0])) return false; //remove spaces at the beginning till not ' ' int start = 0; while(start< size && s[start] == ' ') { start++; } if(start == size) return false; //first letter just if(!possibleFirstChar.Contains(s[start]) && !digits.Contains(s[start])) return false; if(possibleFirstChar.Contains(s[start])) { if(s[start] == '.') { dotindex = start; } start++; } int tempStart = start; int i =tempStart; for(;i<size && s[i] != ' ';i++) { if(s[i] == 'e') { if(eindex >= 0 || numindex < 0) return false;// cannot have 2 'e' && must have digits before e eindex = i; } else if(s[i] == '.') { if(eindex >= 0 || dotindex >= 0) return false; // cannot after '2' && can not have 2 '.' dotindex = i; } else if(s[i] == '+' || s[i] == '-') //should be just after 'e' { if( eindex != i-1) return false; } else if(!digits.Contains(s[i])) return false; else numindex = i; } //check whether we have extra spaces in the end if(i != size) { while(i<size) { if(s[i] !=' ') return false; i++; } }//blank at end if((dotindex==0 && eindex == 1)) return false;// such as .e12; if(numindex < 0 || numindex < eindex) return false;// such as . , e; return true; }