Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing a character with a set of characters c++

Tags:

c++

is there a way to compare a single character with a set of characters?

eg:

char a;
if(a in {'q','w','e','r','t','y','u'})
      return true;
else return false;

i need something like this.

like image 588
Prasanth Madhavan Avatar asked Apr 06 '11 10:04

Prasanth Madhavan


2 Answers

std::string chars = "qwertyu";
char c = 'w';
if (chars.find(c) != std::string::npos) {
  // It's there
}

Or you could use a set - if you need to lookup often that's faster.

std::set<char> chars;
char const * CharList = "qwertyu";
chars.insert(CharList, CharList + strlen(CharList));
if (chars.find('q') != chars.end())  {
  // It's there
}

EDIT: As Steve Jessop's suggested: You can also use chars.count('q') instead of find('q') != end()

You could also use a bitmap of present chars (e.g. vector<bool>) but that's overly complex unless you do this a few million times a second.

like image 169
Erik Avatar answered Nov 06 '22 16:11

Erik


Use strchr:

return strchr("qwertyu", a);

There's no need to write, "if x return true else return false," just, "return x".

like image 24
Marcelo Cantos Avatar answered Nov 06 '22 17:11

Marcelo Cantos