Extract words from the std::set which has the letter 'A' in C++

72 Views Asked by At

I have a set of words (BELLOW, CELLO, HAAF, HABIT, HADAL, HAIR, HELLO, HELP, RABIT) stored in std::set datastructure.

  1. From the above set DS, I want to extract words which starts(0th index) with 'H' and store it other container(say std::setstd::string ctr). Now, ctr will have - HAAF, HABIT, HADAL, HAIR, HELLO, HELP

  2. Now, I want to fetch the words which has the second letter(1st Index) as 'A' from the container ctr. Now, ctr will have - HAAF, HABIT, HADAL, HAIR

  3. I want to fetch the words which has the letter 'A' in any index other than 0th & 1st Indices. Basically, I don't want to check the string 0th and 1st positions.

    Now, ctr will have - HAAF, HADAL

I'm not sure how to do the 3rd step.

#include <iostream>
#include <set>

int main()
{
    std::set<std::string> words = {"BELLOW", "CELLO",  "HAAF", 
                                   "HABIT",  "HADAL", "HAIR",
                                   "HELLO", "HELP", "RABIT"};
    for (const std::string& s : words) {
        std::cout << s << std::endl;    
    }
    
    std::set<std::string> etr;
    
    /* Extract words start with letter 'H' */
    for (const std::string& s : words) {
        if (s[0] == 'H') {
           //std::cout << s << std::endl;  
           etr.insert(s);
        }
    }
    
    std::cout << std::endl;
    
    for (const std::string& s : etr) {
        std::cout << s << std::endl;    
    }
    
    std::set<std::string> etr2;
    
    /* Extract words start with letter 'H' & 
       second letter as 'A' */
    for (const std::string& s : etr) {
        if (s[1] == 'A') {
           //std::cout << s << std::endl;  
           etr2.insert(s);
        }
    }
    
    std::cout << std::endl;
    
    for (const std::string& s : etr2) {
        std::cout << s << std::endl;    
    }
    
    /* Extract words start with letter 'H' & 
       second letter as 'A', and any other letter as 'A'
       but not second letter */
    // << I'm not sure  >>    
      
    return 0;
}

Link for running this program

Solution which I expected:

    for (const std::string& s : etr2) {
        size_t occ = s.find('A');
         // Repeat till end is reached
         while(occ != std::string::npos) {
            if (std::find(pos.begin(), pos.end(), occ) == pos.end()) {
                etr.insert(s);
             }
            // Get the next occurrence from the current position
            occ = s.find('A', occ + 1);
        }
    }

Find the link for this solution

1

There are 1 best solutions below

6
numzero On

The same way you checked other words: iterate over the set, but this time iterate over each word and check whether there is any A in suitable position.

But note that previous checks could be done much more efficiently with std::set as it is sorted, and you need to extract strings between "H" and "I" (I follows H). Two set::lower_bound calls would return you the range.