Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find if a given string conforms to hex notation, eg. 0x34FF without regex?

In regex it would be 0x[0-9a-fA-F]+, but how to achieve it in pure c++ ?

like image 961
rsk82 Avatar asked Jan 17 '12 17:01

rsk82


4 Answers

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;
}
like image 81
Rob Kennedy Avatar answered Nov 16 '22 11:11

Rob Kennedy


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;
}
like image 20
Hayk Avetisyan Avatar answered Nov 16 '22 11:11

Hayk Avetisyan


Call strtoul and check for an error.

like image 3
bmargulies Avatar answered Nov 16 '22 13:11

bmargulies


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;
}
like image 2
JaredPar Avatar answered Nov 16 '22 13:11

JaredPar