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

问题描述 投票:0回答:1

我明白如何在C++中用定界符拆分一个字符串,但如何拆分一个字符串?嵌入 中,例如:尝试将其拆分。”~!hello~! random junk... ~!world~!” 由字符串 ”~!” 变成一系列的 [“hello”, “ random junk...”, “world”]是否有任何C++标准库函数可以实现这个功能,或者如果没有任何算法可以实现这个功能?

c++ string algorithm split delimiter
1个回答
2
投票
#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;
 }

上面的程序会找到所有的 定界符前、中、后出现的字词。 您指定的词。通过对函数的细微改动,你可以使函数适合你的需要(例如,如果你不需要查找出现在第一个分隔符或最后一个分隔符之前的单词)。

但对于你的需求,给定的函数可以做到以下几点 遣词造句 根据您提供的定界符。

我希望这能解决你的问题!

© www.soinside.com 2019 - 2024. All rights reserved.