简体   繁体   English

如何拆分嵌入在 C++ 分隔符中的字符串?

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

I understand how to split a string by a string by a delimiter in C++, but how do you split a string embedded in a delimiter, eg try and split ”~.hello~. random junk... ~!world~!”我了解如何通过 C++ 中的分隔符将字符串拆分为字符串,但是如何拆分嵌入在分隔符中的字符串,例如尝试拆分”~.hello~. random junk... ~!world~!” ”~.hello~. random junk... ~!world~!” by the string ”~!”通过字符串”~!” into an array of [“hello”, “ random junk...”, “world”] ?[“hello”, “ random junk...”, “world”]的数组中? are there any C++ standard library functions for this or if not any algorithm which could achieve this?是否有任何 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;
 }

The above program will find all the words that occur before, in between and after the delimiter that you specify.上面的程序将查找出现在您指定的分隔符之前、中间和之后的所有单词 With minor changes to the function, you can make the function suit your need ( like for example if you don't need to find the word that occurs before the first delimiter or last delimiter).通过对 function 进行细微更改,您可以使 function 满足您的需要(例如,如果您不需要查找出现在第一个分隔符或最后一个分隔符之前的单词)。

But for your need, the given function does the word splitting in the right way according to the delimiter you provide.但是根据您的需要,给定的 function 根据您提供的分隔符以正确的方式进行分词

I hope this solves your question !我希望这能解决你的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM