首页 > 解决方案 > 在字符串中查找项目并说何时找到 - c++

问题描述

我有一串项目(见代码)。我想说何时找到该列表中的特定项目。在我的示例中,我希望输出为 3,因为该项目是在前两项之后找到的。我可以将单独的项目打印到控制台,但我不知道如何计算这两个项目。我认为这是因为 while 循环......我总是得到像 11 这样的数字,而不是两个单独的 1。有小费吗?:)

#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
}

标签: c++stringitems

解决方案


我用方法替换了你的搜索算法explode,它用分隔符分隔你的字符串并返回一个向量,它更适合搜索和获取元素计数:

#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;
}

通过使用std::find_if,您可以获得item1by 迭代器的位置,您可以使用它std::distance来获取它前面的元素的数量。

该方法的功劳explode转到这篇文章:PHP 的explode() 函数在C++ 中是否有等价物?


推荐阅读