多拆分字符串
C++ Multi-split a string
我正试图分割我收到的一些数据,数据是这样的:
0010|chocolate|cookie;458|strawberry|cream;823|peanut|butter;09910|chocolate|icecream
所以首先我需要分隔food
的每个部分(用";"分隔),然后得到仅包含"chocolate"
的food
部分的ID
,问题是数据不是静态的,所以我无法预测food
部分与"chocolate"
将出现多少次。
下面是我分割食物部分并获得数据中部分数量的代码:
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
vector<string> &split(const string &s, char delim, vector<string> &elems)
{
stringstream ss(s);
string item;
while (getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
vector<string> split(const string &s, char delim)
{
vector<string> elems;
split(s, delim, elems);
return elems;
}
char* data = "0010|chocolate|cookie;458|strawberry|cream;823|peanut|butter;09910|chocolate|icecream";
int main()
{
vector<string> food = split(data, ';');
cout << number of food sections is : " << food.size();
return 0;
}
它工作,但现在我想让它在所有部分阅读,并列出我哪些包含"巧克力"在它像:
0010|chocolate|cookie
09910|chocolate|icecream
然后只列出包含chocolate
的部分的ID,这可能与我使用的相同的分割向量是可能的。
0010
09910
这取决于你的数据有多丰富。最终,您必须使用递归下降解析器。但这似乎更简单。
分号可以转义吗?如果没有,就继续,每次遇到分号时,将索引存储在一个增长向量中。这给了你创纪录的开局。然后检查一下记录。创建一个临时字符串,其中包含到分号的记录,然后搜索字符串"chocolate"。如果匹配,则id是记录中的第一个字段,因此直到第一个|字符。
尝试使用函数在由delim分隔的字符串中查找单词,如下所示:
bool find(string vfood, string s, char delim)
{
std::istringstream to_find(vfood);
for (std::string word; std::getline(to_find, word, delim); ) if (word == s) return true;
return false;
}
然后你可以在每个'food'字符串中找到你想要的任何东西
vector<string> food_with_chocolate;
for (string &s : food)
{
if (find(s, "chocolate", '|')) food_with_chocolate.push_back(s);
}
相关文章:
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 将字符串拆分为等长 c++ 的部分
- 如何使用 Boost C++ 打印第 n 个字符串拆分?
- 我在将字符串拆分为向量时遇到困难
- C++ 如何将字符串拆分为单个字符
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 将字符串拆分为单个单词并将它们放置在向量中
- 基于其中的数字子字符串拆分字符串
- 如何在C++中将数字字符串拆分为数组
- 如何在 c++ 中将字符串拆分为字符串 2d 数组数组
- 如何将标准::字符串拆分为标准::string_views的范围 (v3)
- 将特定格式的字符串拆分为浮点数和字符串
- 在 c++ 中将字符串拆分为单独的变量
- 用C 中的4个字符将字符串拆分
- 如何用Arduino中的另一个字符串将字符串拆分
- 如何在 Main 方法之外将字符串拆分为标记
- C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中
- 将字符串拆分为矢量 C++
- 试图将字符串拆分为两个整数