how to find if a given string conforms to hex notation, eg. 0x34FF without regex?
Call strtoul
and check for an error.
With C++11 you can do it easily:
std::string str = "FF22ABCD16ZZ";
if (std::all_of(str.begin(), str.end(), ::isxdigit)) {
std::cout << str << " contains only hexadecimal digits" << std::endl;
}
Try the following
bool IsHex(const std::string& str) {
if (str.length < 3 || str[0] != '0') {
return false;
}
if (str[1] != 'x' && str[1] != 'X') {
return false;
}
for (size_t i = 2; i < str.length; i++) {
char current = str[i];
if (current >= '0' && current <= '9') {
continue;
}
if (current >= 'A' && current <= 'F') {
continue;
}
if (current >= 'a' && current <= 'f') {
continue;
}
return false;
}
return true;
}
You can use the built-in methods of std::string
to check that the first portion of the string is the literal "0x" and that the remainder of the string contains only the allowed characters. Here is the equivalent to the regular expression given in the question:
bool is_hex_notation(std::string const& s)
{
return s.compare(0, 2, "0x") == 0
&& s.size() > 2
&& s.find_first_not_of("0123456789abcdefABCDEF", 2) == std::string::npos;
}