If the string is all numbers
If you are using the .NET framework, there is a Char.IsDigit() method available. Otherwise you could convert characters in a string to their ASCII value and then check to see if the string contains the 0-9 number's ASCII values.
I am guessing there are more ways to do this.
I am guessing there are more ways to do this.
You might want to start here, isdigit, and explore the functions in the run time library until you find one that does what you want.
Quote:Original post by Tradone
Is there a standard way to tell if a string consists of all numbers or not?
What language are we talking about?
Quote:Original post by TradoneIf this is C++, a standard-ish method would be:
Is there a standard way to tell if a string consists of all numbers or not?
if (boost::algorithm::all(myString, boost::algorithm::is_digit()) { // ...}
I don't have the reference in front of me so I might not have gotten the syntax exactly right, but it should be something close to that.
This handles both Hex or Decimal numbers.
(my rating will now go down for suggesting a "C" solution and not a c++ solution)
[Edited by - BeerNutts on April 24, 2006 3:02:13 PM]
BOOL IsNumber(char *cString, BOOL bIsHex){ BOOL bIsDigit = TRUE; while((*cString != 0) && bIsDigit) { if (bIsHex) { bIsDigit = isxdigit(*cString); } else { bIsDigit = isdigit(*cString); } cString++; } return bIsDigit;}
(my rating will now go down for suggesting a "C" solution and not a c++ solution)
[Edited by - BeerNutts on April 24, 2006 3:02:13 PM]
Quote:Original post by BeerNutts
This handles both Hex or Decimal numbers.
*** Source Snippet Removed ***
if (boost::algorithm::all(myString, boost::algorithm::is_xdigit()) { // ...}
:-)
And if for some silly reason you don't like Boost :)
// We need this wrapper to provide typedefs used by not1.struct isDigit { typedef char argument_type; typedef bool result_type; result_type operator() (argument_type x) { return std::is_digit(x); }};if (std::find_if(myString.begin(), myString.end(), std::not1(isDigit())) == myString.end()) { // We didn't find a non-digit, so they are all digits.}
Quote:Original post by jykQuote:Original post by BeerNutts
This handles both Hex or Decimal numbers.
*** Source Snippet Removed ***:-)if (boost::algorithm::all(myString, boost::algorithm::is_xdigit()) { // ...}
Just what I was looking.
Everybody thanks for the contributions!
Also keep in mind that if a string that has "-123.567" is a number you will need to check if "-" and "." are allowed. I do not know if you are interested in the punctuation of a number, but I will leave that up to you.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement