c++ - 在字符串中查找项目并说何时找到 - 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
}
解决方案
我用方法替换了你的搜索算法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
,您可以获得item1
by 迭代器的位置,您可以使用它std::distance
来获取它前面的元素的数量。
该方法的功劳explode
转到这篇文章:PHP 的explode() 函数在C++ 中是否有等价物?
推荐阅读
- javascript - 通过匹配相似列上的元素加入两个多维数组javascript es6
- javascript - react-vis径向饼图的padAngle属性不起作用
- javascript - 使用 javascript 查找没有正确类名或 id 的 html 元素
- git - git pull --porcelain like 选项
- regex - Ruby - 如何返回匹配的正则表达式值
- django - Django查询在另一个字段上应用不同的注释
- c# - 在 .net 4x 和 .net 5 应用程序之间共享身份验证 Cookie - 访问用户声明原则
- laravel - 如何为行添加编号列
- javascript - Bootstrap 中不显示子菜单
- neo4j - Neo4j spring - 在相同类型的实体之间创建 2 向关系