多拆分字符串

C++ Multi-split a string

本文关键字:字符串 拆分      更新时间:2023-10-16

我正试图分割我收到的一些数据,数据是这样的:

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