你如何拆分嵌入在 C++ 中的定界符中的字符串?

how do you split a string embedded in a delimiter in C++?

我了解如何在 C++ 中通过定界符将字符串拆分为字符串,但是如何在定界符中拆分字符串 embedded,例如尝试用字符串 ”~!””~!hello~! random junk... ~!world~!” 拆分为 [“hello”, “ random junk...”, “world”] 的数组?是否有任何 C++ 标准库函数可以实现这一点,或者如果没有任何算法可以实现这一点?

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

vector<string> split(string s,string delimiter){
    vector<string> res;
    s+=delimiter;       //adding delimiter at end of string
    string word;
    int pos = s.find(delimiter);
    while (pos != string::npos) {
        word = s.substr(0, pos);                // The Word that comes before the delimiter
        res.push_back(word);                    // Push the Word to our Final vector
        s.erase(0, pos + delimiter.length());   // Delete the Delimiter and repeat till end of String to find all words
        pos = s.find(delimiter);                // Update pos to hold position of next Delimiter in our String 
    }   
    res.push_back(s);                          //push the last word that comes after the delimiter
    return res;
}

int main() {
        string s="~!hello~!random junk... ~!world~!";
        vector<string>words = split(s,"~!");
        int n=words.size();
        for(int i=0;i<n;i++)
            std::cout<<words[i]<<std::endl;
        return 0;
 }

以上程序将查找出现在您指定的分隔符之前、之间和之后的所有单词。通过对该函数进行微小的更改,您可以使该函数满足您的需要(例如,如果您不需要查找出现在第一个定界符或最后一个定界符之前的单词)。

但根据您的需要,给定的函数根据您提供的分隔符以正确的方式进行单词拆分

希望这能解决您的问题!