Since you asked about using switch statements, I assume that it would be acceptable to have a hard-coded list of 3-letter words and their corresponding letters. In that case, I would solve this problem using a sequence of if-then-else statements, each attempting to match the characters of the 3-letter words. Alternatively, you could use nested switch statements, but the syntax makes that solution a bit harder to read IMO.
static char match_word(std::string const &str, std::size_t offset)
{
char ret = '?';
if (str[offset + 0] == 'c' && str[offset + 1] == 'a' && str[offset + 2] == 't') {
ret = 'P';
}
else if (str[offset + 0] == 'd' && str[offset + 1] == 'o' && str[offset + 2] == 'g') {
ret = 'A';
}
else if (str[offset + 0] == 'm' && str[offset + 1] == 'a' && str[offset + 2] == 't') {
ret = 'T';
}
else if (str[offset + 0] == 't' && str[offset + 1] == 'a' && str[offset + 2] == 'b') {
ret = 'I';
}
else if (str[offset + 0] == 'r' && str[offset + 1] == 'a' && str[offset + 2] == 't') {
ret = 'E';
}
else if (str[offset + 0] == 'l' && str[offset + 1] == 'i' && str[offset + 2] == 'e') {
ret = 'O';
}
else if (str[offset + 0] == 'a' && str[offset + 1] == 't' && str[offset + 2] == 't') {
ret = 'L';
}
return ret;
}
Then you can test the code with a simple main function like this:
int main(int argc, char **argv)
{
if (argc != 2) {
std::cerr << "USAGE: " << argv[0] << " ENCODED" << std::endl;
return 1;
}
else {
std::string example(argv[1]);
for (std::size_t idx = 0; idx < example.size(); idx += 3) {
std::cout << match_word(example, idx);
}
std::cout << std::endl;
return 0;
}
}
Then just run the program with the encoded string as the one and only argument like this:
$ ./a.out catdogmattabratliematdogatt
PATIEOTAL