Search code examples
c++stringitems

Finding item in string and say WHEN it was found - c++


I have a string of items (see code). I want to say when a specific item from that list is found. In my example I want the output to be 3 since the item is found after the first two items. I can print out the separate items to the console but I cannot figure out how to do a count on these two items. I think it is because of the while loop... I always get numbers like 11 instead of two separate 1s. Any tips? :)

#include <iostream>
#include <string>
using namespace std;


int main() {

string items = "box,cat,dog,cat";
string delim = ",";
size_t pos = 0;
string token;
string item1 = "dog";
int count = 0;
`;
 

while ((pos = items.find(delim)) != string::npos)
{
    token = items.substr(0, pos);
    if (token != item1)
    {
        
            cout << token << endl;  //here I would like to increment count for every   
                                    //item before item1 (dog) is found     
         items.erase(0, pos + 1);
        
    }
    else if (token == item1)

    return 0;

    
}


    return 0;      //output: box cat
}

Solution

  • I replaced your search algorithm with the method explode, that separates your string by a delimiter and returns a vector, which is better suited for searching and getting the element count:

    #include <string>
    #include <vector>
    #include <sstream>
    #include <iostream>
    #include <algorithm>
    
    std::vector<std::string> explode(const std::string& s, char delim)
    {
      std::vector<std::string> result;
      std::istringstream iss(s);
      
      for (std::string token; std::getline(iss, token, delim); )
      {
        result.push_back(std::move(token));
      }
          
      return result;
    }
    
    
    int main() 
    {
      std::string items = "box,cat,dog,cat";
      std::string item1 = "dog";
      char delim = ',';
      
      auto resultVec = explode(items, delim);
      
      auto itResult = std::find_if(resultVec.begin(), resultVec.end()
                  , [&item1](const auto& resultString)
                  {
                    return item1 == resultString;
                  });
                    
      if (itResult != resultVec.end())
      {
          auto index(std::distance(resultVec.begin(), itResult) + 1); // index is zero based
                    
          std::cout << index;
      }
                    
      return 0;
    }
    

    By using std::find_if you can get the position of item1 by iterator, which you can use with std::distance to get the count of elements that are in front of it.

    Credits for the explode method go to this post: Is there an equivalent in C++ of PHP's explode() function?