user2881555
user2881555

Reputation: 141

Possible way to store a string in an array to be used in an IF statement

I have the following code it searches for any words that have doesnt have a Q following by a U. Is there any possible way I can crunch this code down so it only uses one if statment but searches each combination?

        if (word1.find("qq") != std::string::npos) {
            cout << word1 << endl;
        }
        if (word1.find("qa") != std::string::npos) {
            cout << word1 << endl;
        }
        //...

Upvotes: 0

Views: 70

Answers (3)

I would store all search strings in a container and then loop over it:

#include <vector>
#include <iostream>

int main(int, char**) {
  std::string word1 = "this is the string to search";
  std::vector<std::string> patterns;
  patterns.push_back("qq");
  patterns.push_back("qa");
  // etc.

  std::vector<std::string>::size_type i; // for better readability
  for (i = 0; i < patterns.size(); i++) {
    if (word1.find(patterns[i]) != std::string::npos) {
      std::cout << word1 << std::endl;
    }
  }
}

Upvotes: 0

patriot
patriot

Reputation: 107

The limitation with this is I don't think it will catch 'quqa'.

 if (word1.find('q') != std::string::npos 
       && word1.find("qu") == std::string::npos)
            cout << word1 << endl;

edit: this will count the number of "q"'s and make sure the number of "qu"'s is the same. I think it's probably more efficient than searching for every literal combination.

size_t stringCount(const std::string& referenceString,
                   const std::string& subString) {

  const size_t step = subString.size();

  size_t count(0);
  size_t pos(0) ;

  while( (pos=referenceString.find(subString, pos)) !=std::string::npos) {
    pos +=step;
    ++count ;
  }

  return count;

}

bool check_qu(const std::string &word1)
{
    int num_q = stringCount(word1, "q");
    return (num_q > 0) ? 
         (stringCount(word1, "qu") == num_q) : true;
}

Upvotes: 2

tele
tele

Reputation: 11

How about this?

const char *string_list[] = {
  "qq",
  "qa",
  "qz",
  ...
};

for (int i = 0; i < sizeof(string_list)/sizeof(*string_list); i++) {
    if (word1.find(string_list[i]) != std::string::npos) {
        cout << word1 << endl
    }

Upvotes: 0

Related Questions